diff --git "a/3702.jsonl" "b/3702.jsonl" new file mode 100644--- /dev/null +++ "b/3702.jsonl" @@ -0,0 +1,738 @@ +{"seq_id":"66038561","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import *\nfrom .forms import *\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\ndef mostrar_empresas(request):\n empresas = Empresa.objects.all()\n return render(request, 'Empresas.html',\n {'empresas': empresas})\n\ndef nova_empresa(request):\n if request.method == \"POST\":\n form = EmpresaForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('mostrar_empresas')\n else:\n form = EmpresaForm()\n return render(request, 'nova_empresa.html',\n {'form': form})\n\ndef mostrar_acoes(request):\n acoes = Acao.objects.all()\n return render(request, 'Acoes.html',\n {'acoes': acoes})\n\ndef nova_acao(request):\n if request.method == \"POST\":\n form = AcaoForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('mostrar_acoes')\n else:\n form = AcaoForm()\n return render(request, 'nova_acao.html',\n {'form': form})\n\ndef mostrar_cotacoes(request):\n cotacoes = Cotacao.objects.all()\n\n return render(request, 'Cotacao.html',\n {'cotacoes': cotacoes})\n\ndef nova_cotacao(request):\n if request.method == \"POST\":\n form = CotacaoForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('mostrar_cotacoes')\n else:\n form = CotacaoForm()\n return render(request, 'nova_cotacao.html',\n {'form': form})","sub_path":"valores/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"1460074","text":"from scipy import misc\nimport numpy as np\nimport numdifftools as nd\nimport random\nimport time\n\ndef simp(x,j,max_iter,max_time): \n y=lambda x:c+np.dot(x,b)+np.dot(x,np.dot(a,np.transpose([x])))\n iteration=0\n tr=x\n start = time.time()\n while max_iter>iteration and time.time() <= start + max_time:\n grad=nd.Gradient(y)([tr])\n t1=tr-grad*beta\n print(\"Iteration \",iteration+1,\"\\n new x:\\n \",t1)\n print(\"J(x):\\n\",y(tr))\n if y(t1)<=j:\n break\n tr=t1\n iteration+=1\n return t1,y(t1)\n\ndef newton(x,j,max_iter,max_time):\n f=lambda x:c+np.dot(x,b)+np.dot(x,np.dot(a,np.transpose([x])))\n iteration=0\n start=time.time()\n while iteration max_left_palindrome:\n return string + string[-max_right_palindrome - 1::-1]\n return string[:max_left_palindrome - 1:-1] + string\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 'ecarace'\nprint(create_palindrome('race'))\n\n# Test 2\n# Correct result => 'elgoogle'\nprint(create_palindrome('google'))","sub_path":"Strings/create_palindrome.py","file_name":"create_palindrome.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"403940895","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nimg = np.load('lat_cal.npy')\n#plt.imshow(depth_table, cmap='gray',clim=(0,1))\nfig,ax = plt.subplots()\ncax = plt.imshow(img, cmap='gray')\ncbar = fig.colorbar(cax)\nplt.show()\n","sub_path":"show_cal.py","file_name":"show_cal.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"205149631","text":"# x = input(\"Enter number:\")\ny = None\nz = \"Harsha\"\n# z[0] = \"K\"\na = [1,2,3]\nb = (1,2,3)\nb = b + (4,5,6)\nctuple = ()\nd = \"I\\'m here\"\ne = \"Hello Brother\"\n# print(e[0::3])\n# print(d)\n# print(\"find\".islower())","sub_path":"PythonPractise/venv30/inputVSrawinput.py","file_name":"inputVSrawinput.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"111837584","text":"# Author: Aditya Dua\n# 28 January, 2018\n\nfrom collections import UserList\nimport math\nimport numpy as np\nfrom typing import Any\n\nfrom spatialmath import base as tr\nfrom spatialmath.base import quaternions as quat\nfrom spatialmath.base import argcheck as argcheck\nfrom spatialmath import pose3d as p3d\n\n\n\n# TODO\n# angle\n# vectorized RPY in and out\n\n\nclass Quaternion(UserList):\n \"\"\"\n A quaternion is a compact method of representing a 3D rotation that has\n computational advantages including speed and numerical robustness.\n\n A quaternion has 2 parts, a scalar s, and a 3-vector v and is typically written:\n q = s \n \"\"\"\n\n def __init__(self, s: Any =None, v=None, check=True, norm=True):\n \"\"\"\n A zero quaternion is one for which M{s^2+vx^2+vy^2+vz^2 = 1}.\n A quaternion can be considered as a rotation about a vector in space where\n q = cos (theta/2) sin(theta/2) \n where is a unit vector.\n :param s: scalar\n :param v: vector\n \"\"\"\n super().__init__()\n\n if s is None and v is None:\n self.data = [np.array([0, 0, 0, 0])]\n\n elif argcheck.isscalar(s) and argcheck.isvector(v, 3):\n self.data = [np.r_[s, argcheck.getvector(v)]]\n\n elif argcheck.isvector(s, 4):\n self.data = [argcheck.getvector(s)]\n\n elif isinstance(s, list):\n if isinstance(s[0], np.ndarray):\n if check:\n assert argcheck.isvectorlist(s, 4), 'list must comprise 4-vectors'\n self.data = s\n elif isinstance(s[0], self.__class__):\n # possibly a list of objects of same type\n assert all(map(lambda x: isinstance(x, self.__class__), s)), 'all elements of list must have same type'\n self.data = [x._A for x in s]\n else:\n raise ValueError('incorrect list')\n\n elif isinstance(s, np.ndarray) and s.shape[1] == 4:\n self.data = [x for x in s]\n\n elif isinstance(s, Quaternion):\n self.data = s.data\n\n else:\n raise ValueError('bad argument to Quaternion constructor')\n\n def append(self, x):\n print('in append method')\n if not isinstance(self, type(x)):\n raise ValueError(\"cant append different type of pose object\")\n if len(x) > 1:\n raise ValueError(\"cant append a pose sequence - use extend\")\n super().append(x._A)\n\n @property\n def _A(self):\n # get the underlying numpy array\n if len(self.data) == 1:\n return self.data[0]\n else:\n return self.data\n\n def __getitem__(self, i):\n #print('getitem', i)\n # return self.__class__(self.data[i])\n return self.__class__(self.data[i])\n\n @property\n def s(q):\n \"\"\"\n :arg q: input quaternion\n :type q: Quaternion, UnitQuaternion\n :return: real part of quaternion\n :rtype: float or numpy.ndarray\n\n - If the quaternion is of length one, a scalar float is returned.\n - If the quaternion is of length >1, a numpy array shape=(N,) is returned.\n \"\"\"\n if len(q) == 1:\n return q._A[0]\n else:\n return np.array([q.s for q in q])\n\n @property\n def v(self):\n \"\"\"\n :return: vector part of quaternion\n :rtype: numpy ndarray\n\n - If the quaternion is of length one, a numpy array shape=(3,) is returned.\n - If the quaternion is of length >1, a numpy array shape=(N,3) is returned.\n \"\"\"\n if len(self) == 1:\n return self._A[1:4]\n else:\n return np.array([q.v for q in self])\n\n @property\n def vec(self):\n \"\"\"\n :return: quaternion expressed as a vector\n :rtype: numpy ndarray\n\n - If the quaternion is of length one, a numpy array shape=(4,) is returned.\n - If the quaternion is of length >1, a numpy array shape=(N,4) is returned.\n \"\"\"\n if len(self) == 1:\n return self._A\n else:\n return np.array([q._A for q in self])\n\n @classmethod\n def pure(cls, v):\n return cls(s=0, v=argcheck.getvector(v, 3), norm=True)\n\n @property\n def conj(self):\n return self.__class__([quat.conj(q._A) for q in self], norm=False)\n\n @property\n def norm(self):\n \"\"\"Return the norm of this quaternion.\n Code retrieved from: https://github.com/petercorke/robotics-toolbox-python/blob/master/robot/Quaternion.py\n Original authors: Luis Fernando Lara Tobar and Peter Corke\n @rtype: number\n @return: the norm\n \"\"\"\n if len(self) == 1:\n return quat.qnorm(self._A)\n else:\n return np.array([quat.qnorm(q._A) for q in self])\n\n @property\n def unit(self):\n \"\"\"Return an equivalent unit quaternion\n Code retrieved from: https://github.com/petercorke/robotics-toolbox-python/blob/master/robot/Quaternion.py\n Original authors: Luis Fernando Lara Tobar and Peter Corke\n @rtype: quaternion\n @return: equivalent unit quaternion\n \"\"\"\n return UnitQuaternion([quat.unit(q._A) for q in self], norm=False)\n\n @property\n def matrix(self):\n return quat.matrix(self._A)\n\n #-------------------------------------------- arithmetic\n\n def inner(self, other):\n assert isinstance(other, Quaternion), 'operands to inner must be Quaternion subclass'\n return self._op2(other, lambda x, y: quat.inner(x, y), list1=False)\n\n def __eq__(self, other):\n assert isinstance(self, type(other)), 'operands to == are of different types'\n return self._op2(other, lambda x, y: quat.isequal(x, y), list1=False)\n\n def __ne__(self, other):\n assert isinstance(self, type(other)), 'operands to == are of different types'\n return self._op2(other, lambda x, y: not quat.isequal(x, y), list1=False)\n\n def __mul__(left, right):\n \"\"\"\n multiply quaternion\n\n :arg left: left multiplicand\n :type left: Quaternion\n :arg right: right multiplicand\n :type left: Quaternion, UnitQuaternion, float\n :return: product\n :rtype: Quaternion\n :raises: ValueError\n\n ============== ============== ============== ================\n Multiplicands Product\n ------------------------------- --------------------------------\n left right type result\n ============== ============== ============== ================\n Quaternion Quaternion Quaternion Hamilton product\n Quaternion UnitQuaternion Quaternion Hamilton product\n Quaternion scalar Quaternion scalar product\n ============== ============== ============== ================\n\n Any other input combinations result in a ValueError.\n\n Note that left and right can have a length greater than 1 in which case:\n\n ==== ===== ==== ================================\n left right len operation\n ==== ===== ==== ================================\n 1 1 1 ``prod = left * right``\n 1 N N ``prod[i] = left * right[i]``\n N 1 N ``prod[i] = left[i] * right``\n N N N ``prod[i] = left[i] * right[i]``\n N M - ``ValueError``\n ==== ===== ==== ================================\n\n \"\"\"\n if isinstance(right, left.__class__):\n # quaternion * [unit]quaternion case\n return Quaternion(left._op2(right, lambda x, y: quat.qqmul(x, y)))\n\n elif argcheck.isscalar(right):\n # quaternion * scalar case\n #print('scalar * quat')\n return Quaternion([right * q._A for q in left])\n\n else:\n raise ValueError('operands to * are of different types')\n\n def __rmul__(right, left):\n \"\"\"\n Pre-multiply quaternion\n\n :arg right: right multiplicand\n :type right: Quaternion,\n :arg left: left multiplicand\n :type left: float\n :return: product\n :rtype: Quaternion\n :raises: ValueError\n\n Premultiplies a quaternion by a scalar. If the right operand is a list,\n the result will be a list .\n\n Example::\n\n q = Quaternion()\n q = 2 * q\n\n :seealso: :func:`__mul__`\n \"\"\"\n # scalar * quaternion case\n return Quaternion([left * q._A for q in right])\n\n def __imul__(left, right):\n \"\"\"\n Multiply quaternion in place\n\n :arg left: left multiplicand\n :type left: Quaternion\n :arg right: right multiplicand\n :type right: Quaternion, UnitQuaternion, float\n :return: product\n :rtype: Quaternion\n :raises: ValueError\n\n Multiplies a quaternion in place. If the right operand is a list,\n the result will be a list.\n\n Example::\n\n q = Quaternion()\n q *= 2\n\n :seealso: :func:`__mul__`\n\n \"\"\"\n return left.__mul__(right)\n\n def __pow__(self, n):\n assert n >= 0, 'n must be >= 0, cannot invert a Quaternion'\n return self.__class__([quat.pow(q._A, n) for q in self])\n\n def __ipow__(self, n):\n return self.__pow__(n)\n\n def __truediv__(self, other):\n raise NotImplemented('Quaternion division not supported')\n\n def __add__(left, right):\n \"\"\"\n add quaternions\n\n :arg left: left addend\n :type left: Quaternion, UnitQuaternion\n :arg right: right addend\n :type right: Quaternion, UnitQuaternion, float\n :return: sum\n :rtype: Quaternion, UnitQuaternion\n :raises: ValueError\n\n ============== ============== ============== ===================\n Operands Sum\n ------------------------------- -----------------------------------\n left right type result\n ============== ============== ============== ===================\n Quaternion Quaternion Quaternion elementwise sum\n Quaternion UnitQuaternion Quaternion elementwise sum\n Quaternion scalar Quaternion add to each element\n UnitQuaternion Quaternion Quaternion elementwise sum\n UnitQuaternion UnitQuaternion Quaternion elementwise sum\n UnitQuaternion scalar Quaternion add to each element\n ============== ============== ============== ===================\n\n Any other input combinations result in a ValueError.\n\n Note that left and right can have a length greater than 1 in which case:\n\n ==== ===== ==== ================================\n left right len operation\n ==== ===== ==== ================================\n 1 1 1 ``prod = left + right``\n 1 N N ``prod[i] = left + right[i]``\n N 1 N ``prod[i] = left[i] + right``\n N N N ``prod[i] = left[i] + right[i]``\n N M - ``ValueError``\n ==== ===== ==== ================================\n\n A scalar of length N is a list, tuple or numpy array.\n A 3-vector of length N is a 3xN numpy array, where each column is a 3-vector.\n \"\"\"\n # results is not in the group, return an array, not a class\n assert isinstance(left, type(right)), 'operands to + are of different types'\n return Quaternion(left._op2(right, lambda x, y: x + y))\n\n def __sub__(left, right):\n \"\"\"\n subtract quaternions\n\n :arg left: left minuend\n :type left: Quaternion, UnitQuaternion\n :arg right: right subtahend\n :type right: Quaternion, UnitQuaternion, float\n :return: difference\n :rtype: Quaternion, UnitQuaternion\n :raises: ValueError\n\n ============== ============== ============== ==========================\n Operands Difference\n ------------------------------- ------------------------------------------\n left right type result\n ============== ============== ============== ==========================\n Quaternion Quaternion Quaternion elementwise sum\n Quaternion UnitQuaternion Quaternion elementwise sum\n Quaternion scalar Quaternion subtract from each element\n UnitQuaternion Quaternion Quaternion elementwise sum\n UnitQuaternion UnitQuaternion Quaternion elementwise sum\n UnitQuaternion scalar Quaternion subtract from each element\n ============== ============== ============== ==========================\n\n Any other input combinations result in a ValueError.\n\n Note that left and right can have a length greater than 1 in which case:\n\n ==== ===== ==== ================================\n left right len operation\n ==== ===== ==== ================================\n 1 1 1 ``prod = left - right``\n 1 N N ``prod[i] = left - right[i]``\n N 1 N ``prod[i] = left[i] - right``\n N N N ``prod[i] = left[i] - right[i]``\n N M - ``ValueError``\n ==== ===== ==== ================================\n\n A scalar of length N is a list, tuple or numpy array.\n A 3-vector of length N is a 3xN numpy array, where each column is a 3-vector.\n \"\"\"\n # results is not in the group, return an array, not a class\n # TODO allow class +/- a conformant array\n assert isinstance(left, type(right)), 'operands to - are of different types'\n return Quaternion(left._op2(right, lambda x, y: x - y))\n\n def _op2(self, other, op, list1=True):\n\n if len(self) == 1:\n if len(other) == 1:\n if list1:\n return [op(self._A, other._A)]\n else:\n return op(self._A, other._A)\n else:\n #print('== 1xN')\n return [op(self._A, x._A) for x in other]\n else:\n if len(other) == 1:\n #print('== Nx1')\n return [op(x._A, other._A) for x in self]\n elif len(self) == len(other):\n #print('== NxN')\n return [op(x._A, y._A) for (x, y) in zip(self, other)]\n else:\n raise ValueError('length of lists to == must be same length')\n\n # def __truediv__(self, other):\n # assert isinstance(other, Quaternion) or isinstance(other, int) or isinstance(other,\n # float), \"Can be divided by a \" \\\n # \"Quaternion, \" \\\n # \"int or a float \"\n # qr = Quaternion()\n # if type(other) is Quaternion:\n # qr = self * other.inv()\n # elif type(other) is int or type(other) is float:\n # qr.s = self.s / other\n # qr.v = self.v / other\n # return qr\n\n # def __eq__(self, other):\n # # assert type(other) is Quaternion\n # try:\n # np.testing.assert_almost_equal(self.s, other.s)\n # except AssertionError:\n # return False\n # if not matrices_equal(self.v, other.v, decimal=7):\n # return False\n # return True\n\n # def __ne__(self, other):\n # if self == other:\n # return False\n # else:\n # return True\n\n def __repr__(self):\n s = ''\n for q in self:\n s += quat.qprint(q._A, file=None) + '\\n'\n s.rstrip('\\n')\n return s\n\n def __str__(self):\n return self.__repr__()\n\n\nclass UnitQuaternion(Quaternion):\n r\"\"\"\n A unit-quaternion is is a quaternion with unit length, that is\n :math:`s^2+v_x^2+v_y^2+v_z^2 = 1`.\n\n A unit-quaternion can be considered as a rotation :math:`\\theta`about a\n unit-vector in space :math:`v=[v_x, v_y, v_z]` where\n :math:`q = \\cos \\theta/2 \\sin \\theta/2 `.\n \"\"\"\n\n def __init__(self, s: Any=None, v=None, norm=True, check=True):\n \"\"\"\n Construct a UnitQuaternion object\n\n :arg norm: explicitly normalize the quaternion [default True]\n :type norm: bool\n :arg check: explicitly check dimension of passed lists [default True]\n :type check: bool\n :return: new unit uaternion\n :rtype: UnitQuaternion\n :raises: ValueError\n\n Single element quaternion:\n\n - ``UnitQuaternion()`` constructs the identity quaternion 1<0,0,0>\n - ``UnitQuaternion(s, v)`` constructs a unit quaternion with specified\n real ``s`` and ``v`` vector parts. ``v`` is a 3-vector given as a\n list, tuple, numpy.ndarray\n - ``UnitQuaternion(v)`` constructs a unit quaternion with specified\n elements from ``v`` which is a 4-vector given as a list, tuple, numpy.ndarray\n - ``UnitQuaternion(R)`` constructs a unit quaternion from an orthonormal\n rotation matrix given as a 3x3 numpy.ndarray. If ``check`` is True\n test the matrix for orthogonality.\n - ``UnitQuaternion(X)`` constructs a unit quaternion from the rotational\n part of ``X`` which is SO3 or SE3 instance. If len(X) > 1 then\n the resulting unit quaternion is of the same length.\n\n Multi-element quaternion:\n\n - ``UnitQuaternion(V)`` constructs a unit quaternion list with specified\n elements from ``V`` which is an Nx4 numpy.ndarray, each row is a\n quaternion. If ``norm`` is True explicitly normalize each row.\n - ``UnitQuaternion(L)`` constructs a unit quaternion list from a list\n of 4-element numpy.ndarrays. If ``check`` is True test each element\n of the list is a 4-vector. If ``norm`` is True explicitly normalize\n each vector.\n \"\"\"\n super().__init__()\n\n if s is None and v is None:\n self.data = [quat.eye()]\n\n elif argcheck.isscalar(s) and argcheck.isvector(v, 3):\n # UnitQuaternion(s, v) s is scalar, v is 3-vector\n q = np.r_[s, argcheck.getvector(v)]\n if norm:\n q = quat.unit(q)\n self.data = [q]\n\n elif argcheck.isvector(s, 4):\n # UnitQuaternion(q) q is 4-vector\n q = argcheck.getvector(s)\n if norm:\n s = quat.unit(s)\n self.data = [s]\n\n elif isinstance(s, list):\n # UnitQuaternion(list)\n if isinstance(s[0], np.ndarray):\n # list of 4-vectors\n if check:\n assert argcheck.isvectorlist(s, 4), 'list must comprise 4-vectors'\n self.data = s\n elif isinstance(s[0], p3d.SO3):\n # list of SO3/SE3\n self.data = [quat.r2q(x.R) for x in s]\n\n elif isinstance(s[0], self.__class__):\n # possibly a list of objects of same type\n assert all(map(lambda x: isinstance(x, type(self)), s)), 'all elements of list must have same type'\n self.data = [x._A for x in s]\n else:\n raise ValueError('incorrect list')\n\n elif isinstance(s, p3d.SO3):\n # UnitQuaternion(x) x is SO3 or SE3\n self.data = [quat.r2q(x.R) for x in s]\n\n elif isinstance(s, np.ndarray) and tr.isrot(s, check=check):\n # UnitQuaternion(R) R is 3x3 rotation matrix\n self.data = [quat.r2q(s)]\n\n elif isinstance(s, np.ndarray) and tr.ishom(s, check=check):\n # UnitQuaternion(T) T is 4x4 homogeneous transformation matrix\n self.data = [quat.r2q(tr.t2r(s))]\n\n elif isinstance(s, np.ndarray) and s.shape[1] == 4:\n if norm:\n self.data = [quat.qnorm(x) for x in s]\n else:\n self.data = [x for x in s]\n\n elif isinstance(s, UnitQuaternion):\n # UnitQuaternion(Q) Q is a UnitQuaternion instance, clone it\n self.data = s.data\n\n else:\n raise ValueError('bad argument to UnitQuaternion constructor')\n\n # def __getitem__(self, i):\n # print('uq getitem', i)\n # #return self.__class__(self.data[i])\n # return self.__class__(self.data[i])\n\n @property\n def R(self):\n return quat.q2r(self._A)\n\n @property\n def vec3(self):\n return quat.q2v(self._A)\n\n # -------------------------------------------- constructor variants\n @classmethod\n def Rx(cls, angle, unit='rad'):\n \"\"\"\n Construct a UnitQuaternion object representing rotation about X-axis\n\n :arg angle: rotation angle\n :type angle: float\n :arg unit: rotation unit 'rad' [default] or 'deg'\n :type unit: str\n :return: new unit-quaternion\n :rtype: UnitQuaternion\n\n - ``UnitQuaternion(theta)`` constructs a unit quaternion representing a\n rotation of `theta` radians about the X-axis.\n - ``UnitQuaternion(theta, 'deg')`` constructs a unit quaternion representing a\n rotation of `theta` degrees about the X-axis.\n\n .. todo:: vectorize\n \"\"\"\n return cls(tr.rotx(angle, unit=unit), check=False)\n\n @classmethod\n def Ry(cls, angle, unit='rad'):\n \"\"\"\n Construct a UnitQuaternion object representing rotation about Y-axis\n\n :arg angle: rotation angle\n :type angle: float\n :arg unit: rotation unit 'rad' [default] or 'deg'\n :type unit: str\n :return: new unit-quaternion\n :rtype: UnitQuaternion\n\n - ``UnitQuaternion(theta)`` constructs a unit quaternion representing a\n rotation of `theta` radians about the Y-axis.\n - ``UnitQuaternion(theta, 'deg')`` constructs a unit quaternion representing a\n rotation of `theta` degrees about the Y-axis.\n\n .. todo:: vectorize\n \"\"\"\n return cls(tr.roty(angle, unit=unit), check=False)\n\n @classmethod\n def Rz(cls, angle, unit='rad'):\n \"\"\"\n Construct a UnitQuaternion object representing rotation about Z-axis\n\n :arg angle: rotation angle\n :type angle: float\n :arg unit: rotation unit 'rad' [default] or 'deg'\n :type unit: str\n :return: new unit-quaternion\n :rtype: UnitQuaternion\n\n - ``UnitQuaternion(theta)`` constructs a unit quaternion representing a\n rotation of `theta` radians about the Z-axis.\n - ``UnitQuaternion(theta, 'deg')`` constructs a unit quaternion representing a\n rotation of `theta` degrees about the Z-axis.\n\n .. todo:: vectorize\n \"\"\"\n return cls(tr.rotz(angle, unit=unit), check=False)\n\n @classmethod\n def Rand(cls, N=1):\n \"\"\"\n Create SO(3) with random rotation\n\n :param N: number of random rotations\n :type N: int\n :return: 3x3 rotation matrix\n :rtype: SO3 instance\n\n - ``SO3.Rand()`` is a random SO(3) rotation.\n - ``SO3.Rand(N)`` is an SO3 object containing a sequence of N random\n rotations.\n\n :seealso: :func:`spatialmath.quaternion.UnitQuaternion.Rand`\n \"\"\"\n return cls([quat.rand() for i in range(0, N)], check=False)\n\n @classmethod\n def Eul(cls, angles, *, unit='rad'):\n r\"\"\"\n Create an SO(3) rotation from Euler angles\n\n :param angles: 3-vector of Euler angles\n :type angles: array_like\n :param unit: angular units: 'rad' [default], or 'deg'\n :type unit: str\n :return: 3x3 rotation matrix\n :rtype: SO3 instance\n\n ``SO3.Eul(ANGLES)`` is an SO(3) rotation defined by a 3-vector of Euler angles :math:`(\\phi, \\theta, \\psi)` which\n correspond to consecutive rotations about the Z, Y, Z axes respectively.\n\n :seealso: :func:`~spatialmath.pose3d.SE3.eul`, :func:`~spatialmath.pose3d.SE3.Eul`, :func:`spatialmath.base.transforms3d.eul2r`\n \"\"\"\n return cls(quat.r2q(tr.eul2r(angles, unit=unit)), check=False)\n\n @classmethod\n def RPY(cls, angles, *, order='zyx', unit='rad'):\n \"\"\"\n Create an SO(3) rotation from roll-pitch-yaw angles\n\n :param angles: 3-vector of roll-pitch-yaw angles\n :type angles: array_like\n :param unit: angular units: 'rad' [default], or 'deg'\n :type unit: str\n :param unit: rotation order: 'zyx' [default], 'xyz', or 'yxz'\n :type unit: str\n :return: 3x3 rotation matrix\n :rtype: SO3 instance\n\n ``SO3.RPY(ANGLES)`` is an SO(3) rotation defined by a 3-vector of roll, pitch, yaw angles :math:`(r, p, y)`\n which correspond to successive rotations about the axes specified by ``order``:\n\n - 'zyx' [default], rotate by yaw about the z-axis, then by pitch about the new y-axis,\n then by roll about the new x-axis. Convention for a mobile robot with x-axis forward\n and y-axis sideways.\n - 'xyz', rotate by yaw about the x-axis, then by pitch about the new y-axis,\n then by roll about the new z-axis. Covention for a robot gripper with z-axis forward\n and y-axis between the gripper fingers.\n - 'yxz', rotate by yaw about the y-axis, then by pitch about the new x-axis,\n then by roll about the new z-axis. Convention for a camera with z-axis parallel\n to the optic axis and x-axis parallel to the pixel rows.\n\n :seealso: :func:`~spatialmath.pose3d.SE3.rpy`, :func:`~spatialmath.pose3d.SE3.RPY`, :func:`spatialmath.base.transforms3d.rpy2r`\n \"\"\"\n return cls(quat.r2q(tr.rpy2r(angles, unit=unit, order=order)), check=False)\n\n @classmethod\n def OA(cls, o, a):\n \"\"\"\n Create SO(3) rotation from two vectors\n\n :param o: 3-vector parallel to Y- axis\n :type o: array_like\n :param a: 3-vector parallel to the Z-axis\n :type o: array_like\n :return: 3x3 rotation matrix\n :rtype: SO3 instance\n\n ``SO3.OA(O, A)`` is an SO(3) rotation defined in terms of\n vectors parallel to the Y- and Z-axes of its reference frame. In robotics these axes are\n respectively called the orientation and approach vectors defined such that\n R = [N O A] and N = O x A.\n\n Notes:\n\n - The A vector is the only guaranteed to have the same direction in the resulting\n rotation matrix\n - O and A do not have to be unit-length, they are normalized\n - O and A do not have to be orthogonal, so long as they are not parallel\n - The vectors O and A are parallel to the Y- and Z-axes of the equivalent coordinate frame.\n\n :seealso: :func:`spatialmath.base.transforms3d.oa2r`\n \"\"\"\n return cls(quat.r2q(tr.oa2r(o, a)), check=False)\n\n @classmethod\n def AngVec(cls, theta, v, *, unit='rad'):\n \"\"\"\n Create an SO(3) rotation matrix from rotation angle and axis\n\n :param theta: rotation\n :type theta: float\n :param unit: angular units: 'rad' [default], or 'deg'\n :type unit: str\n :param v: rotation axis, 3-vector\n :type v: array_like\n :return: 3x3 rotation matrix\n :rtype: SO3 instance\n\n ``SO3.AngVec(THETA, V)`` is an SO(3) rotation defined by\n a rotation of ``THETA`` about the vector ``V``.\n\n Notes:\n\n - If ``THETA == 0`` then return identity matrix.\n - If ``THETA ~= 0`` then ``V`` must have a finite length.\n\n :seealso: :func:`~spatialmath.pose3d.SE3.angvec`, :func:`spatialmath.base.transforms3d.angvec2r`\n \"\"\"\n return cls(quat.r2q(tr.angvec2r(theta, v, unit=unit)), check=False)\n\n @classmethod\n def Omega(cls, w):\n\n return cls(quat.r2q(tr.angvec2r(tr.norm(w), tr.unitvec(w))), check=False)\n\n @classmethod\n def Vec3(cls, vec):\n return cls(quat.v2q(vec))\n\n @classmethod\n def angvec(cls, theta, v, unit='rad'):\n v = argcheck.getvector(v, 3)\n argcheck.isscalar(theta)\n theta = argcheck.getunit(theta, unit)\n return UnitQuaternion(s=math.cos(theta / 2), v=math.sin(theta / 2) * tr.unit(v), norm=False)\n\n def __truediv__(self, other):\n assert isinstance(self, type(other)), 'operands to * are of different types'\n return self._op2(other, lambda x, y: quat.qqmul(x, quat.conj(y)))\n\n @property\n def inv(self):\n return UnitQuaternion([quat.conj(q._A) for q in self])\n\n @classmethod\n def omega(cls, w):\n assert argcheck.isvector(w, 3), 'w must be a 3-vector'\n w = argcheck.getvector(w)\n theta = tr.norm(w)\n s = math.cos(theta / 2)\n v = math.sin(theta / 2) * tr.unitvec(w)\n return cls(s=s, v=v)\n\n @staticmethod\n def qvmul(qv1, qv2):\n return quat.vvmul(qv1, qv2)\n\n def dot(self, omega):\n return tr.dot(self._A, omega)\n\n def dotb(self, omega):\n return tr.dotb(self._A, omega)\n\n def __mul__(left, right):\n \"\"\"\n Multiply unit quaternion\n\n :arg left: left multiplicand\n :type left: UnitQuaternion\n :arg right: right multiplicand\n :type left: UnitQuaternion, Quaternion, 3-vector, 3xN array, float\n :return: product\n :rtype: Quaternion, UnitQuaternion\n :raises: ValueError\n\n ============== ============== ============== ================\n Multiplicands Product\n ------------------------------- --------------------------------\n left right type result\n ============== ============== ============== ================\n UnitQuaternion Quaternion Quaternion Hamilton product\n UnitQuaternion UnitQuaternion UnitQuaternion Hamilton product\n UnitQuaternion scalar Quaternion scalar product\n UnitQuaternion 3-vector 3-vector vector rotation\n UnitQuaternion 3xN array 3xN array vector rotations\n ============== ============== ============== ================\n\n Any other input combinations result in a ValueError.\n\n Note that left and right can have a length greater than 1 in which case:\n\n ==== ===== ==== ================================\n left right len operation\n ==== ===== ==== ================================\n 1 1 1 ``prod = left * right``\n 1 N N ``prod[i] = left * right[i]``\n N 1 N ``prod[i] = left[i] * right``\n N N N ``prod[i] = left[i] * right[i]``\n N M - ``ValueError``\n ==== ===== ==== ================================\n\n A scalar of length N is a list, tuple or numpy array.\n A 3-vector of length N is a 3xN numpy array, where each column is a 3-vector.\n\n :seealso: :func:`~spatialmath.Quaternion.__mul__`\n \"\"\"\n if isinstance(left, right.__class__):\n # quaternion * quaternion case (same class)\n return right.__class__(left._op2(right, lambda x, y: quat.qqmul(x, y)))\n\n elif argcheck.isscalar(right):\n # quaternion * scalar case\n #print('scalar * quat')\n return Quaternion([right * q._A for q in left])\n\n elif isinstance(right, (list, tuple, np.ndarray)):\n #print('*: pose x array')\n if argcheck.isvector(right, 3):\n v = argcheck.getvector(right)\n if len(left) == 1:\n # pose x vector\n #print('*: pose x vector')\n return quat.qvmul(left._A, argcheck.getvector(right, 3))\n\n elif len(left) > 1 and argcheck.isvector(right, 3):\n # pose array x vector\n #print('*: pose array x vector')\n return np.array([tr.qvmul(x, v) for x in left._A]).T\n\n elif len(left) == 1 and isinstance(right, np.ndarray) and right.shape[0] == 3:\n return np.array([tr.qvmul(left._A, x) for x in right.T]).T\n else:\n raise ValueError('bad operands')\n else:\n raise ValueError('UnitQuaternion: operands to * are of different types')\n\n def __imul__(left, right):\n \"\"\"\n Multiply unit quaternion in place\n\n :arg left: left multiplicand\n :type left: UnitQuaternion\n :arg right: right multiplicand\n :type right: UnitQuaternion, Quaternion, float\n :return: product\n :rtype: UnitQuaternion, Quaternion\n :raises: ValueError\n\n Multiplies a quaternion in place. If the right operand is a list,\n the result will be a list.\n\n Example::\n\n q = UnitQuaternion()\n q *= 2\n\n :seealso: :func:`__mul__`\n\n \"\"\"\n return left.__mul__(right)\n\n def __truediv__(left, right):\n assert isinstance(left, type(right)), 'operands to / are of different types'\n return UnitQuaternion(left._op2(right, lambda x, y: tr.qqmul(x, tr.conj(y))))\n\n def __pow__(self, n):\n return self.__class__([quat.pow(q._A, n) for q in self])\n\n def __eq__(left, right):\n return left._op2(right, lambda x, y: quat.isequal(x, y, unitq=True), list1=False)\n\n def __ne__(left, right):\n return left._op2(right, lambda x, y: not quat.isequal(x, y, unitq=True), list1=False)\n\n def interp(self, s=0, dest=None, shortest=False):\n \"\"\"\n Algorithm source: https://en.wikipedia.org/wiki/Slerp\n :param qr: UnitQuaternion\n :param shortest: Take the shortest path along the great circle\n :param s: interpolation in range [0,1]\n :type s: float\n :return: interpolated UnitQuaternion\n \"\"\"\n # TODO vectorize\n\n if dest is not None:\n # 2 quaternion form\n assert isinstance(dest, UnitQuaternion)\n if s == 0:\n return self\n elif s == 1:\n return dest\n q1 = self.vec\n q2 = dest.vec\n else:\n # 1 quaternion form\n if s == 0:\n return UnitQuaternion()\n elif s == 1:\n return self\n\n q1 = quat.eye()\n q2 = self.vec\n\n assert 0 <= s <= 1, 's must be in interval [0,1]'\n\n dot = quat.inner(q1, q2)\n\n # If the dot product is negative, the quaternions\n # have opposite handed-ness and slerp won't take\n # the shorter path. Fix by reversing one quaternion.\n if shortest:\n if dot < 0:\n q1 = - q1\n dot = -dot\n\n dot = np.clip(dot, -1, 1) # Clip within domain of acos()\n theta_0 = math.acos(dot) # theta_0 = angle between input vectors\n theta = theta_0 * s # theta = angle between v0 and result\n if theta_0 == 0:\n return UnitQuaternion(q1)\n\n s1 = float(math.cos(theta) - dot * math.sin(theta) / math.sin(theta_0))\n s2 = math.sin(theta) / math.sin(theta_0)\n out = (q1 * s1) + (q2 * s2)\n return UnitQuaternion(out)\n\n def __repr__(self):\n s = ''\n for q in self:\n s += quat.qprint(q._A, delim=('<<', '>>'), file=None) + '\\n'\n s.rstrip('\\n')\n return s\n\n def __str__(self):\n return self.__repr__()\n\n def plot(self, *args, **kwargs):\n tr.trplot(tr.q2r(self._A), *args, **kwargs)\n\n @property\n def rpy(self, unit='rad', order='zyx'):\n return tr.tr2rpy(self.R, unit=unit, order=order)\n\n @property\n def eul(self, unit='rad', order='zyx'):\n return tr.tr2eul(self.R, unit=unit)\n\n @property\n def angvec(self, unit='rad'):\n return tr.tr2angvec(self.R)\n\n @property\n def SO3(self):\n return p3d.SO3(self.R, check=False)\n\n @property\n def SE3(self):\n return p3d.SE3(tr.r2t(self.R), check=False)\n\n\nif __name__ == '__main__': # pragma: no cover\n x = p3d.SE3()\n x.append(x)\n q = UnitQuaternion(x)\n print(q)\n import pathlib\n import os.path\n\n exec(open(os.path.join(pathlib.Path(__file__).parent.absolute(), \"test_quaternion.py\")).read())\n","sub_path":"spatialmath/quaternion.py","file_name":"quaternion.py","file_ext":"py","file_size_in_byte":36805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"218272264","text":"# Copyright 2016 - Alcatel-Lucent\n# Copyright 2016 - Nokia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport itertools\n\nfrom oslo_log import log\nfrom oslo_service import service as os_service\nfrom oslo_utils import importutils as utils\nfrom vitrage.datasources.listener_service import ListenerService\n\nfrom services import ChangesService\nfrom services import SnapshotsService\nfrom vitrage.common.utils import opt_exists\n\nLOG = log.getLogger(__name__)\nCHANGES_INTERVAL = 'changes_interval'\n\n\ndef create_send_to_queue_callback(queue):\n def send_to_queue_callback(event):\n queue.put(event)\n\n return send_to_queue_callback\n\n\nclass Launcher(object):\n def __init__(self, conf, callback):\n self.conf = conf\n self.callback = callback\n self.snapshot_datasources = self._register_snapshot_datasources()\n self.services = self._register_services()\n\n def launch(self):\n launcher = os_service.ProcessLauncher(self.conf)\n for service in self.services:\n launcher.launch_service(service, 1)\n\n def _register_snapshot_datasources(self):\n return {plugin: utils.import_object(self.conf[plugin].driver,\n self.conf)\n for plugin in self.conf.datasources.types}\n\n def _register_services(self):\n return itertools.chain(\n (ChangesService(self.conf,\n [self.snapshot_datasources[plugin]],\n self.conf[plugin].changes_interval,\n self.callback)\n\n for plugin in self.conf.datasources.types\n if opt_exists(self.conf[plugin], CHANGES_INTERVAL)),\n\n (SnapshotsService(self.conf,\n self.snapshot_datasources,\n self.callback),),\n\n (ListenerService(self.conf,\n self.snapshot_datasources,\n self.callback),),)\n","sub_path":"vitrage/datasources/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"487779200","text":"\nimport bpy\nfrom math import *\nimport mathutils\nimport time\n\n\nstepsAzimuth= 20 #20 steps for left limit to right limit.\nstepsInclination= 20 #10 steps to upper limit to lower limit.\n\nlight = bpy.data.objects[\"Point\"]\n\n#init distance of rotation to the y position of the light\nradiiRotation= light.location[1];\n\nlimitDegrees= 90\nlimitRadians= limitDegrees*2*pi/360\n\nstepAzimuth= 2*limitRadians/stepsAzimuth #the 2 multiplication is for going from the -limit to the limit.\nstepInclination= 2*limitRadians/stepsInclination #the 2 multiplication is for going from the -limit to the limit. \n\nazimuth= [-limitRadians-pi/2 + i*stepAzimuth for i in range(0,stepsAzimuth+1)]\ninclination= [i*stepInclination for i in range(0,stepsInclination+1)]\nlight = bpy.data.objects[\"Point\"]\n\n#init distance of rotation to the y position of the light\nradiiRotation= -light.location[1];\n\nfor a in azimuth:\n for i in inclination:\n xPosition= cos(a)*sin(i)*radiiRotation\n yPosition= sin(a)*sin(i)*radiiRotation\n zPosition= cos(i)*radiiRotation\n\n \n newPosition= mathutils.Vector((xPosition+0.5,yPosition,zPosition))\n light.location= newPosition\n \n bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)\n bpy.context.scene.update()\n \n #directory= 'C:/Users/Victor/Desktop/Platform/AcquisitionPlatform/Other/ExtraFunctionalities/LightRecovering/lightPoint/'\n directory= 'C:/Users/vmoyano/Documents/GitHub/AcquisitionPlatform/Other/ExtraFunctionalities/LightRecovering/lightPoint2/'\n bpy.data.scenes[\"Scene\"].render.filepath = directory+ 'Azimuth_%f_Inclination_%f_x_%f_y_%f_z_%f.jpg' % ((a+pi/2)*360/(2*pi), i*360/(2*pi), xPosition, -yPosition, -zPosition) \n #bpy.data.scenes[\"Scene\"].render.filepath = directory+ 'x_%f_y_%f_z_%f.jpg' % (xPosition, -yPosition, -zPosition) \n bpy.ops.render.render( write_still=True )\n ","sub_path":"Other/ExtraFunctionalities/Blender Scripts/rotateLights.py","file_name":"rotateLights.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"412076356","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport csv\nfrom time import sleep\nimport pandas as pd\nimport json\nimport urllib.request\nimport os\nfrom PIL import Image\nimport glob\nimport sys\nimport argparse\nimport urllib.parse\nimport hashlib\n\ndef parse_args(args=sys.argv[1:]):\n \"\"\" Get the parsed arguments specified on this script.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"\")\n\n parser.add_argument(\n 'collection_uri',\n action='store',\n type=str,\n help='collection uri.')\n\n parser.add_argument(\n 'output_file_path',\n action='store',\n type=str,\n help='output file path.')\n\n parser.add_argument(\n 'tmp_dir_path',\n action='store',\n type=str,\n help='tmp dir path.')\n\n return parser.parse_args(args)\n\nargs = parse_args()\n\ncollection_uri = args.collection_uri\n\nopath = args.output_file_path\n\ntmp_dir = args.tmp_dir_path\n\nsize = 10\n\nresult = {}\naggregations = {}\naggregations2 = {}\n\ndata = []\nresult[\"rows\"] = data\n\nconfig = {\n \"searchableFields\": [],\n \"sortings\": {\n \"Title Asc\": {\n \"field\": '_label',\n \"order\": 'asc'\n },\n \"Title Desc\": {\n \"field\": '_label',\n \"order\": 'desc'\n }\n },\n \"aggregations\": aggregations2\n}\n\nresult[\"config\"] = config\n\nconfig[\"searchableFields\"].append(\"_label\")\nconfig[\"searchableFields\"].append(\"_description\")\nconfig[\"searchableFields\"].append(\"_fulltext\")\n\n\ndef exec2collection(collection_uri):\n\n print(collection_uri)\n\n collection_uri = urllib.parse.quote(collection_uri, safe='/:?=')\n\n try:\n response = urllib.request.urlopen(collection_uri)\n except Exception as e: ###おかしい\n print(e)\n\n collection = json.loads(response.read().decode('utf8'))\n\n if \"collections\" in collection:\n for c in collection[\"collections\"]:\n exec2collection(c[\"@id\"])\n else:\n exec2manifest(collection[\"manifests\"])\n\n\ndef exec2manifest(manifests):\n for i in range(len(manifests)):\n\n manifest_uri = manifests[i][\"@id\"]\n\n print(str(i+1)+\"/\"+str(len(manifests)))\n\n id = hashlib.md5(manifest_uri.encode('utf-8')).hexdigest()\n\n tmp_file = tmp_dir+\"/\"+id+\".json\"\n\n if not os.path.exists(tmp_file):\n\n response = urllib.request.urlopen(manifest_uri)\n manifest = json.loads(response.read().decode('utf8'))\n\n f2 = open(tmp_file, 'w')\n json.dump(manifest, f2, ensure_ascii=False, indent=4,\n sort_keys=True, separators=(',', ': '))\n else:\n\n try:\n with open(tmp_file) as f:\n manifest = json.load(f)\n except Exception as e:\n print(tmp_file+\"\\t\"+e)\n continue\n\n\n thumbnail = None\n if \"thumbnail\" in manifest:\n if \"@id\" in manifest[\"thumbnail\"]:\n thumbnail = manifest[\"thumbnail\"][\"@id\"]\n else:\n thumbnail = manifest[\"thumbnail\"]\n\n fulltext = \"\"\n\n obj = {\n \"_label\": manifest[\"label\"],\n \"_manifest\": manifest[\"@id\"]\n }\n\n obj[\"_thumbnail\"] = thumbnail\n\n if \"related\" in manifest:\n obj[\"_related\"] = manifest[\"related\"]\n\n if \"description\" in manifest:\n obj[\"_description\"] = manifest[\"description\"]\n\n if \"metadata\" in manifest:\n for metadata in manifest[\"metadata\"]:\n label = metadata[\"label\"]\n value = metadata[\"value\"]\n\n if label == \"description\":\n label = \"description_\"\n\n if isinstance(value, list):\n values = value\n else:\n values = [value]\n\n for value in values:\n\n if value == None:\n continue\n\n value = str(value)\n\n if \"http\" not in value:\n\n if label not in aggregations:\n aggregations[label] = {\n \"title\": label,\n \"map\": {}\n }\n\n if label not in obj:\n obj[label] = []\n\n map = aggregations[label][\"map\"]\n\n if value not in map:\n map[value] = 0\n\n map[value] = map[value] + 1\n\n obj[label].append(value)\n fulltext += \" \"+value\n\n obj[\"_fulltext\"] = fulltext\n data.append(obj)\n\n\nexec2collection(collection_uri)\n\nfor field in aggregations:\n obj = aggregations[field]\n map = obj[\"map\"]\n map = sorted(map.items(), key=lambda kv: kv[1], reverse=True)\n\n if map[0][1] > 1 and len(map) != 1:\n aggregations2[field] = {\n \"title\": obj[\"title\"],\n \"size\": size\n }\n\nf2 = open(opath, 'w')\njson.dump(result, f2, ensure_ascii=False, indent=4,\n sort_keys=True, separators=(',', ': '))\n","sub_path":"src/collection_converter.py","file_name":"collection_converter.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"388789064","text":"import pygame\nimport pygame.freetype\n\nclass Leader(pygame.sprite.Sprite):\n maingame = None\n\n def __init__(self, leaderid, squadposition, armyposition, battalion, leaderstat):\n self._layer = 10\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.morale = 100\n stat = leaderstat.leaderlist[leaderid]\n self.gameid = leaderid # Different than unit game id, leadergameid is only used as reference to the id data\n self.name = stat[0]\n self.health = stat[1]\n self.authority = stat[2]\n self.meleecommand = stat[3]\n self.rangecommand = stat[4]\n self.cavcommand = stat[5]\n self.combat = stat[6] * 10\n self.social = leaderstat.leaderclass[stat[7]]\n self.description = stat[-1]\n self.squadpos = squadposition # Squad position is the index of squad in squad sprite loop\n # self.trait = stat\n # self.skill = stat\n self.state = 0 ## 0 = alive, 96 = retreated, 97 = captured, 98 = missing, 99 = wound, 100 = dead\n if self.name == \"none\":\n self.health = 0\n self.state = 100 ## no leader is same as dead so no need to update\n self.battalion = battalion\n # self.mana = stat\n self.gamestart = 0\n self.armyposition = armyposition\n self.baseimgposition = [(134, 185), (80, 235), (190, 235), (134, 283)]\n self.imgposition = self.baseimgposition[self.armyposition]\n ## put leader image into leader slot\n try:\n self.fullimage = leaderstat.imgs[leaderstat.imgorder.index(leaderid)].copy()\n except: ## Use Unknown leader image if there is none in list\n self.fullimage = leaderstat.imgs[-1].copy()\n self.image = pygame.transform.scale(self.fullimage, (50, 50))\n self.rect = self.image.get_rect(center=self.imgposition)\n self.image_original = self.image.copy()\n self.badmorale = (20, 30) ## other position morale lost\n self.commander = False\n self.originalcommander = False\n if self.armyposition == 0:\n squadpenal = int((self.squadpos / len(self.battalion.armysquad[0])) * 10) # Authority get reduced the further leader stay in the back line\n self.authority = self.authority - ((self.authority * squadpenal / 100) / 2)\n self.badmorale = (30, 50) ## main general morale lost when die\n if self.battalion.commander:\n self.commander = True\n self.originalcommander = True\n\n def poschangestat(self, leader):\n \"\"\"Change stat that related to army position such as in leader dead event\"\"\"\n leader.badmorale = (20, 30) ## sub general morale lost for bad event\n if leader.armyposition == 0:\n squadpenal = int((leader.squadpos / len(leader.battalion.armysquad[0])) * 10)\n leader.authority = leader.authority - ((leader.authority * squadpenal / 100) / 2)\n leader.badmorale = (30, 50) ## main general morale lost for bad event\n\n def gone(self):\n eventtext = {96:\"retreat\",97:\"captured\",98:\"missing\",99:\"wounded\",100:\"dead\"}\n if self.commander and self.battalion.leader[3].state not in (96, 97, 98, 99, 100) and self.battalion.leader[3].name != \"None\":\n ## If commander die will use strategist as next commander first\n print('test')\n self.battalion.leader[0], self.battalion.leader[3] = self.battalion.leader[3], self.battalion.leader[0]\n elif self.battalion.leader[1].state not in (96, 97, 98, 99, 100) and self.battalion.leader[1].name != \"None\":\n self.battalion.leader.append(self.battalion.leader.pop(self.armyposition)) ## move leader to last of list when dead\n thisbadmorale = self.badmorale[0]\n if self.state == 99: # wonnd inflict less morale penalty\n thisbadmorale = self.badmorale[1]\n for squad in self.battalion.squadsprite:\n squad.basemorale -= thisbadmorale ## decrease all squad morale when leader die depending on position\n if self.commander: ## reduce morale to whole army if commander die from the dmg (leader die cal is in gameleader.py)\n self.maingame.textdrama.queue.append(str(self.name) + \" is \" + eventtext[self.state])\n eventmapid = \"ld0\"\n whicharmy = self.maingame.playerarmy\n if self.battalion.gameid >= 2000:\n whicharmy = self.maingame.enemyarmy\n eventmapid = \"ld1\"\n if self.originalcommander:\n self.maingame.eventlog.addlog([0, \"Commander \" + str(self.name) + \" is \" + eventtext[self.state]], [0, 1, 2], eventmapid)\n else: self.maingame.eventlog.addlog([0, \"Commander \" + str(self.name) + \" is \" + eventtext[self.state]], [0, 1, 2])\n for army in whicharmy:\n for squad in army.squadsprite:\n squad.basemorale -= 100\n else:\n self.maingame.eventlog.addlog([0, str(self.name) + \" is \" + eventtext[self.state]], [0, 2])\n for index, leader in enumerate(self.battalion.leader): ## also change army position of all leader in that battalion\n leader.armyposition = index ## change army position to new one\n if self.battalion.commander and leader.armyposition == 0:\n self.commander = True\n leader.imgposition = leader.baseimgposition[leader.armyposition]\n leader.rect = leader.image.get_rect(center=leader.imgposition)\n self.poschangestat(leader)\n self.battalion.commandbuff = [(self.battalion.leader[0].meleecommand - 5) * 0.1, (self.battalion.leader[0].rangecommand - 5) * 0.1,\n (self.battalion.leader[0].cavcommand - 5) * 0.1]\n self.authority = 0\n self.meleecommand = 0\n self.rangecommand = 0\n self.cavcommand = 0\n self.combat = 0\n self.social = 0\n pygame.draw.line(self.image, (150, 20, 20), (5, 5), (45, 35), 5)\n self.maingame.setuparmyicon()\n self.battalion.leaderchange = True\n\n def update(self):\n if self.gamestart == 0:\n self.squad = self.battalion.squadsprite[self.squadpos]\n self.gamestart = 1\n if self.state not in (96, 97, 98, 99, 100):\n if self.health <= 0:\n self.health = 0\n self.state = 100\n # if random.randint(0,1) == 1: self.state = 99 ## chance to become wound instead when hp reach 0\n self.gone()\n \n","sub_path":"gamescript/gameleader.py","file_name":"gameleader.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"59028209","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass QiaobujlspiderPipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nimport sqlite3\n\n\nclass SqlitePipeline(object):\n def __init__(self, db_name):\n if not db_name:\n db_name = \"db.sqlite\"\n self.con = sqlite3.connect(db_name)\n self.cursor = self.con.cursor()\n\n def close_spider(self):\n self.cursor.close()\n self.con.close()\n self.cursor = None\n self.con = None\n\n @classmethod\n def from_settings(cls, settings): # 从setting里面传值\n db_name = settings[\"DB_NAME\"]\n return cls(db_name)\n\n def process_item(self, item, spider):\n create_table_last_part = \"\"\n insert_lie_name = []\n insert_lie_value = []\n for key, value in item.items():\n if isinstance(value, str):\n lie_type = \" VARCHAR(255),\"\n elif isinstance(value, int):\n lie_type = \" INTEGER,\"\n elif isinstance(value, float):\n lie_type = \" FLOAT,\"\n elif isinstance(value, list):\n lie_type = \" VARCHAR(255),\"\n value = \"|\".join(value)\n insert_lie_name.append(key)\n insert_lie_value.append(value)\n create_table_last_part += key + lie_type\n sql1 = f\"\"\"CREATE TABLE IF NOT EXISTS {spider.name}(id INTEGER PRIMARY KEY AUTOINCREMENT,{create_table_last_part\n [:-1]})\"\"\"\n self.cursor.execute(sql1)\n sql2 = f\"\"\"INSERT INTO {spider.name} ({\",\".join(insert_lie_name)}) VALUES ({(\"?,\" * len(insert_lie_name))[\n :-1]})\"\"\"\n self.cursor.execute(sql2, insert_lie_value)\n self.con.commit()\n return item\n\n\nfrom scrapy.pipelines.images import ImagesPipeline\nfrom scrapy import Request\nimport hashlib\n\n\nclass MyImagesPipeline(ImagesPipeline):\n # 1.需要修改文件后缀\n # 2.获取对应的存储路径\n # 3.缩略图后缀及存储路径\n\n def file_path(self, request, response=None, info=None):\n # url = request.url # 这个url是当前请求的url(也就是配置文件传来的url) 而并非item中的url\n\n path1 = request.meta[\"intention_title\"]\n path2 = request.meta[\"title\"] # request\n information = f'full/{path1}/{path2}.jpg'\n print(f\"图片下载成功 文件信息: {information} \")\n return information\n\n def item_completed(self, results, item, info):\n if results:\n item[\"list_img_path\"] = results[0][1][\"path\"]\n else:\n item[\"list_img_path\"] = \"没有找到\" # 重写路径results\n # print(item)\n # print(\"=============\", results)\n return item\n\n def get_media_requests(self, item, info):\n # 从管道中获取图片的地址,和名称\n # print(\"----\", item)\n yield Request(url=item[\"list_img_src\"][0],\n meta={'intention_title': item['intention_title'], \"title\": item[\"title\"]}) # 这里要取第0个\n","sub_path":"QiaobujlSpider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"396869155","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#.--. .-. ... .... -. - ... .-.-.- .. -.\n\nfrom datetime import datetime\nimport dateutil.parser\nimport requests\n\nfrom blinker import signal\nfrom functools import reduce\nfrom flask import Flask, Blueprint, render_template, request, jsonify\nfrom flask_restful import Resource, reqparse\nfrom flask.ext.security import current_user, login_required\n\nfrom survaider import app\nfrom survaider.minions.decorators import api_login_required\nfrom survaider.review.model import ReviewsAggregator\nimport json\n\nreview = Blueprint('review', __name__, template_folder = 'templates')\n\nclass DateTimeEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, datetime):\n return o.isoformat()\n\n return json.JSONEncoder.default(self, o)\n\n\nclass ReviewAggregation(Resource):\n\n @api_login_required\n def get(self):\n \treviews = ReviewsAggregator(current_user.id).get()\n \treturn_reviews = []\n \tobj = {}\n \tfor review in reviews:\n obj = {}\n obj['survey_id'] = review.survey_id\n obj['rating'] = review.rating\n obj['review'] = review.review\n obj['provider'] = review.provider\n obj['sentiment'] = review.sentiment\n obj['date_added'] = json.dumps(review.date_added, cls=DateTimeEncoder)\n obj['review_link'] = review.review_link\n return_reviews.append(obj)\n \treturn return_reviews\n\n @api_login_required\n def post(self):\n pass\n\n@review.route('/')\ndef review_home():\n return render_template(\"reviewspage.html\", title = \"Review\")","sub_path":"survaider/review/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"35210020","text":"from mxnet import nd,autograd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom mxnet.gluon import data as gdata\nfrom mxnet.gluon import nn\nfrom mxnet import init\nfrom mxnet.gluon import loss as gloss\nfrom mxnet import gluon\n#求梯度的例子\n# x=nd.arange(4).reshape((-1,1))\n# x.attach_grad()\n# with autograd.record():\n# y = 2 * nd.dot(x.T, x)\n# y.backward()\n# print(x.grad)\n\n#线性规划原始写法\n# n_samples=1000\n# n_inputs=2\n# X=nd.random_normal(shape=(n_samples,n_inputs))\n# true_W=nd.array([2,-3.4]).reshape((-1,1))\n# true_b=4.2\n# y=nd.dot(X,true_W)+true_b\n# y+=1e-2*nd.random_normal(scale=1,shape=y.shape)\n# \n# #小批量样本生成函数\n# def data_iter(batch_size, features, labels):\n# num_examples = len(features)\n# indices = list(range(num_examples))\n# random.shuffle(indices) # 样本的读取顺序是随机的\n# for i in range(0, num_examples, batch_size):\n# j = nd.array(indices[i: min(i + batch_size, num_examples)])\n# yield features.take(j), labels.take(j) # take函数根据索引返回对应元素\n# \n# w=nd.random_normal(shape=(n_inputs,1))\n# b=nd.zeros(shape=1)\n# w.attach_grad()\n# b.attach_grad()\n# def linreg(x, W, c):\n# return nd.dot(x, W) + c\n# \n# def squared_loss(y_hat,y):\n# return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2\n# \n# def sgd(params, alpha, batch_size):\n# for param in params:\n# param[:] = param - alpha * param.grad / batch_size\n# \n# lr = 0.03\n# num_epochs = 200\n# net = linreg\n# loss = squared_loss\n# b_size=10\n# for epoch in range(num_epochs):\n# for train_x,train_y in data_iter(b_size,X,y):\n# with autograd.record():\n# l=loss(net(train_x,w,b),train_y)\n# l.backward()\n# sgd([w,b],lr,b_size)\n# print(loss(net(X,w,b),y).mean().asnumpy())\n# print(w)\n# print(b)\n\n#线性回归简洁实现\nnum_inputs=2\nnum_examples=1000\ntrue_w=nd.array([2,-3.4]).reshape((-1,1))\ntrue_b=4.2\nfeatures=nd.random.normal(scale=1,shape=(num_examples,num_inputs))\nlabels=nd.dot(features,true_w)+true_b\nlabels+=nd.random.normal(scale=0.01,shape=labels.shape)\n\nbatch_size=10\ndataset = gdata.ArrayDataset(features,labels)\ndata_iter=gdata.DataLoader(dataset,batch_size,shuffle=True)\n\n#Sequential是串联各层的容器\nnet=nn.Sequential()\n#Dense是全连接层,1表示该层输出的变量的数目,输入变量的数目会自动确定\nnet.add(nn.Dense(1))\n#权重参数高斯随机初始化\nnet.initialize(init.Normal(sigma=0.01))\n\n#平方损失\nloss=gloss.L2Loss()\n\n#定义优化算法\ntrainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})\n#训练\nnum_epochs=3\nfor epoch in range(1,num_epochs+1):\n for X,y in data_iter:\n with autograd.record():\n l = loss(net(X),y)\n l.backward()\n trainer.step(batch_size)\n l=loss(net(features),labels)\n print('epoch %d, loss:%f'%(epoch,l.mean().asnumpy()))\n\nprint(net[0].weight.data())\nprint(net[0].bias.data()) \n","sub_path":"lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162321844","text":"# coding: utf-8\n\n\nimport json\nimport os\nimport shutil\nimport unittest\n\nimport numpy as np\n\nfrom pymongo import MongoClient\n\nfrom fireworks import LaunchPad, FWorker\nfrom fireworks.core.rocket_launcher import rapidfire\n\nfrom atomate.utils.testing import AtomateTest\nfrom atomate.vasp.powerups import use_fake_vasp\nfrom atomate.vasp.workflows.base.ferroelectric import get_wf_ferroelectric\nfrom atomate.utils.utils import get_a_unique_id\nfrom atomate.vasp.firetasks.parse_outputs import PolarizationToDb\n\nfrom pymatgen import SETTINGS\n\n__author__ = 'Tess Smidt'\n__email__ = 'blondegeek@gmail.com'\n\nmodule_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))\ndb_dir = os.path.join(module_dir, \"..\", \"..\", \"..\", \"common\", \"test_files\")\nref_dir = os.path.join(module_dir, \"..\", \"..\", \"test_files\")\n\nfrom pymatgen.core.structure import Structure\n\nDEBUG_MODE = False # If true, retains the database and output dirs at the end of the test\nVASP_CMD = None # If None, runs a \"fake\" VASP. Otherwise, runs VASP with this command...\n\n@unittest.skip(\"This workflow may require a set of POTCARs and corresponding .pmgrc.yaml file.\")\nclass TestFerroelectricWorkflow(AtomateTest):\n\n def setUp(self):\n super(TestFerroelectricWorkflow, self).setUp()\n\n self.bto_polar = Structure.from_file(ref_dir+\"/ferroelectric_wf/\"+\"BTO_polar_POSCAR\")\n self.bto_nonpolar = Structure.from_file(ref_dir+\"/ferroelectric_wf/\"+\"BTO_nonpolar_POSCAR\")\n\n self.wfid = \"wfid_\" + get_a_unique_id()\n\n self.ferroelectric_config = {'vasp_cmd': '>>vasp_cmd<<',\n 'db_file': '>>db_file<<',\n 'nimages': 2,\n 'relax' : True,\n 'wfid': self.wfid,\n 'add_analysis_task': False}\n\n self.wf = get_wf_ferroelectric(self.bto_polar, self.bto_nonpolar, **self.ferroelectric_config)\n\n if not os.path.exists(os.path.join(ref_dir, \"ferroelectric_wf\", \"nonpolar_static\")):\n self.untarTestFiles()\n\n def untarTestFiles(self):\n import tarfile\n tar_filename = os.path.abspath(os.path.join(ref_dir, \"ferroelectric_wf\",\n \"test_ferroelectric_workflow.gz.tar\"))\n print(tar_filename)\n t = tarfile.open(tar_filename)\n t.extractall(os.path.abspath(os.path.join(ref_dir, \"ferroelectric_wf\")))\n\n def _simulate_vasprun(self, wf):\n reference_dir = os.path.abspath(os.path.join(ref_dir, \"ferroelectric_wf\"))\n bto_ref_dirs = {\"_polar_relaxation\": os.path.join(reference_dir, \"polar_relaxation\"),\n \"_polar_static\": os.path.join(reference_dir, \"polar_static\"),\n \"_polar_polarization\": os.path.join(reference_dir, \"polar_polarization\"),\n \"_nonpolar_relaxation\": os.path.join(reference_dir, \"nonpolar_relaxation\"),\n \"_nonpolar_static\": os.path.join(reference_dir, \"nonpolar_static\"),\n \"_nonpolar_polarization\": os.path.join(reference_dir, \"nonpolar_polarization\"),\n \"_interpolation_1_static\": os.path.join(reference_dir, \"interpolation_1_static\"),\n \"_interpolation_1_polarization\": os.path.join(reference_dir, \"interpolation_1_polarization\")}\n # Add test with for analysis?\n # Which params_to_check?\n return use_fake_vasp(wf, bto_ref_dirs, params_to_check=[\"ENCUT\", \"LWAVE\"])\n\n def _check_run(self, d, mode):\n\n # Check polar and nonpolar relaxations\n if mode == '_polar_relaxation':\n self.assertAlmostEqual(d[\"calcs_reversed\"][0][\"output\"][\"structure\"][\"lattice\"][\"c\"], 4.2157, 2)\n\n if mode == '_nonpolar_relaxation':\n self.assertAlmostEqual(d[\"calcs_reversed\"][0][\"output\"][\"structure\"][\"lattice\"][\"c\"], 4.0350, 2)\n\n # Check interpolated structure\n if mode == '_interpolation_1_polarization':\n self.assertAlmostEqual(d[\"calcs_reversed\"][0][\"output\"][\"structure\"][\"lattice\"][\"c\"], 4.1345, 2)\n\n # Check that Outcar has needed keys for polarization analysis.\n if '_polarization' in mode and 'processing' not in mode:\n # Check that Outcar has p_ion, p_elec, zval_dict\n assert d[\"calcs_reversed\"][0][\"output\"][\"outcar\"].get(\"p_ion\", None) is not None\n assert d[\"calcs_reversed\"][0][\"output\"][\"outcar\"].get(\"p_elec\", None) is not None\n assert d[\"calcs_reversed\"][0][\"output\"][\"outcar\"].get(\"zval_dict\", None) is not None\n\n # Check analysis step.\n if mode == \"_polarization_post_processing\":\n self.assertAlmostEqual(d['polarization_change_norm'], 46.288752795325244)\n\n def test_wf(self):\n\n self.wf = self._simulate_vasprun(self.wf)\n\n # 2*relax + 3*polarization = 5\n self.assertEqual(len(self.wf.fws), 5)\n\n # check VASP parameters on polarization calculation for interpolated structures\n interpolated_polarization_vis = [fw.tasks[7]['incar_update']['lcalcpol']\n for fw in self.wf.fws if \"polarization\" in fw.name and \"interpolation\" in fw.name]\n\n assert all(interpolated_polarization_vis)\n\n self.lp.add_wf(self.wf)\n rapidfire(self.lp, fworker=FWorker(env={\"db_file\": os.path.join(db_dir, \"db.json\")}))\n\n # Check polar relaxation\n d = self.get_task_collection().find_one({\"task_label\": \"_polar_relaxation\"})\n self._check_run(d, \"_polar_relaxation\")\n\n # Check nonpolar relaxation\n d = self.get_task_collection().find_one({\"task_label\": \"_nonpolar_relaxation\"})\n self._check_run(d, \"_nonpolar_relaxation\")\n\n # Check polarization calculations\n D = self.get_task_collection().find({\"task_label\": {\"$regex\": \".*polarization\"}})\n for d in D:\n self._check_run(d, d[\"task_label\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"atomate/vasp/workflows/tests/test_ferroelectric_workflow.py","file_name":"test_ferroelectric_workflow.py","file_ext":"py","file_size_in_byte":5945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"103105370","text":"#%% IMPORT\n\nimport pandas as pd\nimport numpy as np\nimport math\nfrom sklearn.decomposition import PCA\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom behavelet import wavelet_transform\n\n#%% Functions \n\nlabels_num = {'abdominal_pushing' : 0, 'anterior_grooming' : 1, 'posterior_grooming' : 2, 'walking' : 3, 'resting' : 4}\n\ndef compute_label_distribution(labels):\n nb_sample_per_label = []\n unique_labels = np.unique(labels)\n for label in unique_labels:\n nb_sample_per_label.append((labels == label).sum().item())\n return unique_labels, nb_sample_per_label\n\ndef balance_dataset(x, y):\n unique_labels, nb_sample_per_label = compute_label_distribution(y)\n nb_samples_per_class = max(nb_sample_per_label)\n x_balanced = np.empty([0, np.size(x,1)])\n y_balanced = np.empty(0)\n for label in unique_labels:\n indices = (y == label)\n samples = x[indices]\n labels = y[indices]\n while 2*np.size(samples,0) < nb_samples_per_class:\n samples = np.concatenate([samples, samples], axis=0)\n labels = np.concatenate([labels, labels], axis=0)\n samples = np.concatenate([samples, samples[:(nb_samples_per_class-np.size(samples,0))]], axis=0)\n labels = np.concatenate([labels, labels[:(nb_samples_per_class-np.size(labels,0))]], axis=0)\n x_balanced = np.concatenate([x_balanced, samples], axis=0)\n y_balanced = np.concatenate([y_balanced, labels], axis=0)\n indices_suffled = np.random.permutation(np.size(y_balanced,0))\n x_balanced = x_balanced[indices_suffled]\n y_balanced = y_balanced[indices_suffled]\n return x_balanced, y_balanced\n \n\ndef create_data_set(beh_angles, beh_labels, val_ratio, test_ratio):\n\n y=np.empty(np.size(beh_labels,0))\n \n x = beh_angles\n y[:] = [labels_num[p] for p in beh_labels]\n \n #Shuffle dataset\n indices_suffled = np.random.permutation(np.size(y,0))\n x = x[indices_suffled]\n y = y[indices_suffled]\n \n # Create dataset\n test_split = math.floor(test_ratio*np.size(x,0))\n val_split = math.floor((test_ratio+val_ratio)*np.size(x,0))\n x_test = x[:test_split]\n y_test = y[:test_split]\n x_val = x[test_split:val_split]\n y_val = y[test_split:val_split]\n x_train = x[val_split:]\n y_train = y[val_split:]\n \n x_train, y_train = balance_dataset(x_train, y_train)\n \n return x_train, y_train, x_val, y_val, x_test, y_test\n\n#%% LOADING DATA\nneur_df = pd.read_pickle(\"COBAR_behaviour_incl_manual_corrected.pkl\")\nangles = beh_df.filter(regex=\"angle\").values\nlabels = beh_df[\"Manual\"].values\n\n#%% PCA \nPCA_object = PCA(n_components=17)\nangles_proj = PCA_object.fit_transform(angles)\nsum_proj = sum(PCA_object.explained_variance_ratio_)\n\n#%% WAVELET\nfreqs, power, angles_wav = wavelet_transform(angles_proj, n_freqs=25, fsample=100., fmin=1., fmax=50.)\n\n#%% EXTRACT DATA\nval_ratio = 0.2\ntest_ratio = 0.3\ntrain_ratio = 0.5\n\nx_train, y_train, x_val, y_val, x_test, y_test = create_data_set(angles_wav, labels, val_ratio, test_ratio)\n\n#%% RANDOM FOREST CLASSIFICATION\nprint(\"Start Random Forest\")\nclf_forest = RandomForestClassifier(max_depth=10, random_state=0)\nclf_forest.fit(x_train, y_train)\n\nscore_forest = clf_forest.score(x_test, y_test)\n\n\n#%% SVM\nprint(\"Start SVM\")\nclf_svm = svm.SVC() \nclf_svm.fit(x_train, y_train)\n# clf_svm_26 = svm.SVC(C=10, kernel='sigmoid', gamma=1) \n# clf_svm_26.fit(x_train, y_train)\n# clf_svm_41 = svm.SVC(C=100, kernel='sigmoid', gamma=0.1) \n# clf_svm_41.fit(x_train, y_train)\n#%% SVM score\nscore_test_svm = clf_svm.score(x_test, y_test)\n# score_test_svm_26 = clf_svm_26.score(x_test, y_test)\n# score_test_svm_41 = clf_svm_41.score(x_test, y_test)\n\n#%% SVM Grid Search\n\n# param_grid = {'C': [0.1,1, 10, 100], 'gamma': [1,0.1,0.01,0.001],'kernel': ['rbf', 'poly', 'sigmoid']}\n# grid = GridSearchCV(svm.SVC(),param_grid,refit=True,verbose=2)\n# grid.fit(angles_train, labels_train)\n\n#%%\n# best_ind = grid.cv_results_['params'][grid.best_index_]\n# print(best_ind)\n# best_sc = grid.best_score_\n# print(best_sc)\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%\n#%%","sub_path":"matthieu/old/Classifying_neur.py","file_name":"Classifying_neur.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"431353457","text":"# -*- coding: utf-8 -*-\n\"\"\"\n flaskbb.utils.markup\n ~~~~~~~~~~~~~~~~~~~~\n\n A module for all markup related stuff.\n\n :copyright: (c) 2016 by the FlaskBB Team.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport logging\nimport re\n\nimport mistune\nfrom flask import url_for\nfrom jinja2 import Markup\nfrom pluggy import HookimplMarker\nfrom pygments import highlight\nfrom pygments.formatters import HtmlFormatter\nfrom pygments.lexers import get_lexer_by_name\nfrom pygments.util import ClassNotFound\n\nimpl = HookimplMarker('flaskbb')\n\nlogger = logging.getLogger(__name__)\n\n_re_user = re.compile(r'@(\\w+)', re.I)\n\n\ndef userify(match):\n value = match.group(1)\n user = \"@{user}\".format(\n url=url_for(\"user.profile\", username=value, _external=False),\n user=value\n )\n return user\n\n\nclass FlaskBBRenderer(mistune.Renderer):\n \"\"\"Markdown with some syntactic sugar, such as @user gettting linked\n to the user's profile.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(FlaskBBRenderer, self).__init__(**kwargs)\n\n def paragraph(self, text):\n \"\"\"Render paragraph tags, autolinking user handles.\"\"\"\n\n text = _re_user.sub(userify, text)\n return super(FlaskBBRenderer, self).paragraph(text)\n\n def block_code(self, code, lang):\n if lang:\n try:\n lexer = get_lexer_by_name(lang, stripall=True)\n except ClassNotFound:\n lexer = None\n else:\n lexer = None\n if not lexer:\n return '\\n
%s
\\n' % \\\n mistune.escape(code)\n formatter = HtmlFormatter()\n return highlight(code, lexer, formatter)\n\n\n@impl\ndef flaskbb_load_post_markdown_class():\n return FlaskBBRenderer\n\n\n@impl\ndef flaskbb_load_nonpost_markdown_class():\n return FlaskBBRenderer\n\n\n@impl\ndef flaskbb_jinja_directives(app):\n render_classes = app.pluggy.hook.flaskbb_load_post_markdown_class(app=app)\n app.jinja_env.filters['markup'] = make_renderer(render_classes)\n\n render_classes = app.pluggy.hook.flaskbb_load_nonpost_markdown_class(\n app=app\n )\n app.jinja_env.filters['nonpost_markup'] = make_renderer(render_classes)\n\n\ndef make_renderer(classes):\n RenderCls = type('FlaskBBRenderer', tuple(classes), {})\n\n markup = mistune.Markdown(renderer=RenderCls(escape=True, hard_wrap=True))\n return lambda text: Markup(markup.render(text))\n","sub_path":"flaskbb/markup.py","file_name":"markup.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"304725252","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.core.paginator import Paginator\n\nimport json\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.shortcuts import HttpResponse, HttpResponseRedirect, render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import User, Post, Comment, Follower, Like\n\n\n#def index(request):\n# return render(request, \"network/index.html\")\n\n\ndef index(request):\n # If no user is signed in, return to login page:\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(\"login\"))\n return render(request, \"network/index.html\")\n\n\ndef login_view(request):\n if request.method == \"POST\":\n\n # Attempt to sign user in\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n\n # Check if authentication successful\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"network/login.html\", {\n \"message\": \"Invalid username and/or password.\"\n })\n else:\n return render(request, \"network/login.html\")\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"index\"))\n\n\ndef register(request):\n if request.method == \"POST\":\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n\n # Ensure password matches confirmation\n password = request.POST[\"password\"]\n confirmation = request.POST[\"confirmation\"]\n if password != confirmation:\n return render(request, \"network/register.html\", {\n \"message\": \"Passwords must match.\"\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(username, email, password)\n user.save()\n except IntegrityError:\n return render(request, \"network/register.html\", {\n \"message\": \"Username already taken.\"\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"network/register.html\")\n\n@csrf_exempt\n@login_required\ndef plus_like(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n #content = data.get(\"content\")\n w_post = data.get(\"w_post\")\n post = Post.objects.get(pk=w_post)\n user = request.user\n if Like.objects.filter(user=user,post=post).exists():\n Like.objects.filter(user=user, post=post).delete()\n liked = False\n else:\n like = Like(\n user=user,\n post=post\n )\n like.save()\n liked = True\n counter = Like.objects.filter(post=post).count()\n return JsonResponse({\n \"Success\": \"like added\",\n \"likecount\":str(counter),\n \"liked\":liked\n }, status=200)\n return JsonResponse({\n \"Error\": \"get methode\"\n }, status=400)\n\n ###############################\n\n@csrf_exempt\n@login_required\ndef cancel_like(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n #content = data.get(\"content\")\n w_post = data.get(\"w_post\")\n post = Post.objects.get(pk=w_post)\n user = request.user\n\n like = Like(\n user=user,\n post=post\n )\n like.delete()\n counter = Like.objects.filter(post=post).count()\n return JsonResponse({\n \"Success\": \"like canceled\",\n \"likecount\":str(counter)\n }, status=200)\n return JsonResponse({\n \"Error\": \"get methode\"\n }, status=400)\n\n ###############################\n\n@csrf_exempt\n@login_required\ndef likecounter(request,id):\n post = Post.objects.get(pk=id)\n counter = Like.objects.filter(post=post).count()\n liked = False\n if Like.objects.filter(user=request.user, post=post).exists():\n liked = True\n\n return JsonResponse({\n \"likecount\":str(counter),\n \"liked\":liked\n }, status=200)\n\n@csrf_exempt\n@login_required\ndef like_button(request,id):\n #post = Post.objects.get(pk=id)\n post = Post.objects.get(pk=id)\n #counter = Like.objects.filter(post=post).count()\n like_button = Like.objects.filter(post=post).filter(user=request.user).count()\n return JsonResponse({\n \"like_button\":str(like_button)\n }, status=200)\n\n@csrf_exempt\n@login_required\ndef compose(request):\n\n # Composing a new email must be via POST\n if request.method != \"POST\":\n return JsonResponse({\"error\": \"POST request required.\"}, status=400)\n\n # Check recipient emails\n data = json.loads(request.body)\n\n content = data.get(\"content\")\n\n if content == \"\":\n return JsonResponse({\n \"error\": \"Empty post is not permitted.\"\n }, status=400)\n\n\n creator = User.objects.get(username=request.user.username)\n post = Post(\n creator=creator,\n content=content\n )\n\n post.save()\n\n return JsonResponse({\"message\": \"Post sent successfully.\"}, status=201)\n\n ######################################################################\n\ndef all_posts(request):\n post_list = Post.objects.all()\n post_list = post_list.order_by(\"-time_of_creation\").all()\n paginator = Paginator(post_list, 10) # Show 10 contacts per page.\n page_number = request.GET.get('page', 1)\n page_obj = paginator.get_page(page_number)\n return render(request, 'network/all_posts.html', {'page_obj': page_obj})\n\n#########################################################################3\n\ndef comment(request, post_id):\n post = Post.objects.get(id=post_id)\n #comments_0 = Comment.objects.all()\n comments = Comment.objects.all().filter(item_id=post.id)\n return render(request, \"network/comment.html\", {\n \"post\": post,\n \"comments\": comments\n })\n\ndef edit(request, post_id):\n post = Post.objects.get(id=post_id)\n return render(request, \"network/edit.html\", {\n \"post\": post\n })\n\n@csrf_exempt\n@login_required\ndef edit_2(request, post_id):\n # Query for requested post\n try:\n post = Post.objects.get(pk=post_id)\n except Post.DoesNotExist:\n return JsonResponse({\"error\": \"Post not found.\"}, status=404)\n\n # Return post contents\n if request.method == \"GET\":\n return JsonResponse(post.serialize())\n\n # Update whether email is read or should be archived\n elif request.method == \"PUT\":\n data = json.loads(request.body.decode(\"utf-8\"))\n print(post.content)\n post.content = data[\"content\"]\n post.save()\n return JsonResponse({\n \"Success\": \"Update\"\n }, status=200)\n\n # Post must be via GET or PUT\n else:\n return JsonResponse({\n \"error\": \"GET or PUT request required.\"\n }, status=400)\n\n\ndef comment_add(request, post_id):\n username = request.user.username\n user = User.objects.get(username=username)\n post = Post.objects.get(id=post_id)\n if request.method == \"POST\":\n comment = request.POST[\"comment\"]\n comments = Comment.objects.create(user=user, post=post, comment=comment, item_id=post.id)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return HttpResponse(\"Invalid Input\")\n\n\ndef profile(request, creator_id):\n username = request.user.username\n user = User.objects.get(username=username)\n user2 = User.objects.get(id=creator_id)\n #Airport.objects.filter(city=\"New York\")\n post_list = Post.objects.filter(creator=user2)\n post_list = post_list.order_by(\"-time_of_creation\").all()\n paginator = Paginator(post_list, 10) # Show 10 contacts per page.\n page_number = request.GET.get('page',)\n page_obj = paginator.get_page(page_number)\n wells = Follower.objects.all().filter(user=user)\n y_cont = Follower.objects.all().filter(user=user).count()\n w_cont = Follower.objects.all().filter(user=user2).count()\n cont = 0\n for well in wells:\n if well.following == user2:\n cont = cont + 1\n\n x_cont = user.followed.all().count()\n z_cont = user2.followed.all().count()\n #for well in wells:\n # if well.following == user2:\n # w_cont = W_cont + 1\n return render(request, 'network/profile.html', {'page_obj': page_obj, 'user': user, 'user2': user2, \"w_cont\": int(w_cont), \"x_cont\": int(x_cont), \"z_cont\": int(z_cont), 'y_cont': int(y_cont), 'cont': int(cont)})\n\n\ndef follower_add(request, following_id):\n following = User.objects.get(id=following_id)\n username = request.user.username\n user = User.objects.get(username=username)\n #follower_items = Follower.objects.all()\n item_count = Follower.objects.all().filter(user=user, following=following).count()\n if item_count == 1:\n return HttpResponse(\"Following\")\n follower_item = Follower.objects.create(user=user, following=following)\n #my_follower = Follower.objects.all().get(user=user)\n return HttpResponseRedirect(reverse(\"index\"))\n #return render(request, \"network/follower_add.html\", {\n # \"message\": \"from now on, following this user, as long as you don't decide to stop following it\"\n # \"my_follower\": my_follower\n #})\n\n\ndef follower_index(request):\n username = request.user.username\n user = User.objects.get(username=username)\n wells = Follower.objects.all().filter(user=user)\n post_list = Post.objects.all()\n w_list = []\n for well in wells:\n follower = well.following\n w_list.append(follower)\n post_list = Post.objects.filter(creator__in=w_list)\n #post_list = Post.objects.filter(creator=user2)\n #Blog.objects.filter(pk__in=[1, 4, 7])\n post_list = post_list.order_by(\"-time_of_creation\").all()\n paginator = Paginator(post_list, 10) # Show 10 contacts per page.\n page_number = request.GET.get('page',)\n page_obj = paginator.get_page(page_number)\n return render(request, 'network/follower_index.html', {'page_obj': page_obj, 'user': user})\n\n\n\ndef follower_del(request, following_id):\n following = User.objects.get(id=following_id)\n username = request.user.username\n user = User.objects.get(username=username)\n well = Follower.objects.get(user=user, following=following)\n well.delete()\n return HttpResponseRedirect(reverse(\"index\"))\n","sub_path":"network/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"111352527","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n################################################################################\n##\n## inorder+Preorder/Postorder/Levelorder can define a binary Tree\n##\n################################################################################\n\n## https://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/\n\nclass Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n def preorder_encode_tree(root,preorder_dic):\n if not root:\n return tuple([-1]) # this is important, return an empty tuple will make trouble\n preorder_dic[root]= tuple([root.val])+preorder_encode_tree(root.left,preorder_dic)+preorder_encode_tree(root.right,preorder_dic)\n return preorder_dic[root] \n \n def inorder_encode_tree(root,inorder_dic):\n if not root:\n return tuple([-1])\n inorder_dic[root]= inorder_encode_tree(root.left,inorder_dic)+tuple([root.val])+inorder_encode_tree(root.right,inorder_dic)\n return inorder_dic[root]\n preorder_dic={}\n inorder_dic={}\n preorder_encode_tree(root,preorder_dic)\n inorder_encode_tree(root,inorder_dic)\n coded_node={}\n out = set()\n for node in preorder_dic:\n if (preorder_dic[node],inorder_dic[node]) not in coded_node:\n coded_node[(preorder_dic[node],inorder_dic[node])]=node\n else:\n out.add(coded_node[(preorder_dic[node],inorder_dic[node])])\n return out\n \n","sub_path":"Problem652_Find_Duplicate_Subtrees.py","file_name":"Problem652_Find_Duplicate_Subtrees.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"449655206","text":"from pssplot.pssfigure import Pssfigure\nfrom pssplot.pssplot import test_pssplot\nfrom collections import defaultdict\n\nFILE_PATH = 'test.py'\nfigure = Pssfigure(FILE_PATH)\n\nprint(figure._plots)\n\nprint(figure._plots['test'])\nfigure._plots['test'] = 'hello'\nprint(figure._plots['test'])\n\n# Create test plots\nplt1 = test_pssplot('plt1')\nplt2 = test_pssplot('plt2')\nplt3 = test_pssplot('plt3')\nplt4 = test_pssplot('plt3')\n# plt2 = dict(file_path='test2.py')\n# plt3 = dict(file_path='test3.py', other_var=5)\n# plt4 = dict(file_path='test3.py', other_var=4)\n\nplots = [plt1, plt2, plt3, plt4]\n\ntest_dict = defaultdict(list)\n\nfor plot in plots:\n value = plot.name\n test_dict[value].append(plot)\n\nfor plot, figure in test_dict.items():\n print(plot)\n for plt in figure:\n plt.test_plot()","sub_path":"test_pssfigure.py","file_name":"test_pssfigure.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"526274449","text":"'''\nrefer : https://github.com/mbr/tinyrpc/tree/master/examples\nimport gevent\nimport tinyrpc\nimport gevent-websocket\n'''\n\nfrom tinyrpc.protocols.jsonrpc import JSONRPCProtocol\nfrom tinyrpc.transports.http import HttpPostClientTransport\nfrom tinyrpc import RPCClient\n\nrpc_client = RPCClient(\n JSONRPCProtocol(),\n HttpPostClientTransport('http://127.0.0.1:5000/')\n)\n\nremote_server = rpc_client.get_proxy()\n\n# call a method called 'reverse_string' with a single string argument\nresult = remote_server.reverse_string('Hello, World!')\n\nprint(\"Server answered: \", result)","sub_path":"ZMQ/zmq_tinyrpc_http_client.py","file_name":"zmq_tinyrpc_http_client.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"312236111","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# script for auditing and formatting postal codes in an OSM file\nimport re\n\nnonalpha_re = re.compile('\\W')\n\n# returns the set of postal codes used in an osm file\ndef audit_postal_code(osmfile):\n osm_file = open(osmfile, \"r\")\n postal_codes = set()\n for event, elem in ET.iterparse(osm_file, events=(\"start\",)):\n\n if elem.tag == \"node\" or elem.tag == \"way\":\n for tag in elem.iter(\"tag\"):\n if tag.attrib['k'] == \"addr:postcode\":\n postal_codes.add(tag.attrib['v'])\n\n osm_file.close()\n return postal_codes\n\n# takes a postal code and returns it in the proper format or returns None if given an invalid postal code\ndef format_postal_code(code):\n # strip any BC prefix\n if code[0:2].upper() == 'BC':\n code = code[2:]\n # strip all non alphanumeric characters\n code = re.sub(nonalpha_re, \"\", code)\n # insert a space to the middle of the code\n code = code[0:3] + ' ' + code[3:]\n return code.upper()[0:7] if len(code) > 6 else None","sub_path":"Cleaning Vancouver OSM Data/audit_postal_codes.py","file_name":"audit_postal_codes.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"511823074","text":"# 組み込みのClassifierやTrainerを使わず,単純パーセプトロンを最適化する\nimport time\nimport sys\n\nimport numpy as np\n\nimport chainer\nimport chainer.links as L\nimport chainer.functions as F\nfrom chainer import report, computational_graph\nfrom chainer import optimizers, serializers\nfrom chainer import Chain\n\nfrom net import SimplePerceptron\nfrom net import Classifier\n\nbatchsize = 100\nn_epoch = 100\n\n# training data size\nN = int(input())\n\n# データセットを標準入力から読み込む\ntrain_data_raw = []\ntrain_target_raw = []\nfor i in range(0, N):\n i0, i1, t = input().split()\n train_data_raw.append([i0, i1])\n train_target_raw.append(t)\n# NumPy配列に変換\ntrain_data = np.array(train_data_raw, dtype=\"float32\")\ntrain_target = np.array(train_target_raw, dtype=\"int32\")\n\n# モデルインスタンスの作成\nmodel = Classifier(SimplePerceptron())\n\n# オプティマイザの初期化\noptimizer = optimizers.Adam()\noptimizer.setup(model)\n\n# トレーニングループ\nfor epoch in range(0, n_epoch):\n print ('epoch', epoch+1)\n\n # ランダムに訓練データを並べ替える\n perm = np.random.permutation(N)\n sum_accuracy = 0\n sum_loss = 0\n\n start = time.time()\n for i in range(0, N, batchsize):\n # データを取り出し\n x = chainer.Variable(np.asarray(train_data[perm[i:i + batchsize]]))\n t = chainer.Variable(np.asarray(train_target[perm[i:i + batchsize]]))\n\n # オプティマイズ\n optimizer.update(model, x, t)\n\n # グラフ出力(一回だけ)\n if epoch == 0 and i == 0:\n with open('graph.dot', 'w') as o:\n variable_style = {'shape': 'octagon', 'fillcolor': '#E0E0E0',\n 'style': 'filled'}\n function_style = {'shape': 'record', 'fillcolor': '#6495ED',\n 'style': 'filled'}\n g = computational_graph.build_computational_graph(\n (model.loss, ),\n variable_style=variable_style,\n function_style=function_style)\n o.write(g.dump())\n print('graph generated')\n\n sum_loss += float(model.loss.data) * len(t.data)\n sum_accuracy += float(model.accuracy.data) * len(t.data)\n end = time.time()\n elapsed_time = end - start\n throughput = N / elapsed_time\n\n print('train mean loss={}, accuracy={}, throughput={} images/sec'.format(\n sum_loss / N, sum_accuracy / N, throughput))\n\nprint('save the model') \nserializers.save_npz('linear.model', model)\n\n","sub_path":"simple-perceptron/train_linear.py","file_name":"train_linear.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"232489243","text":"__author__ = 'Tianlu.Shi'\n\nclass RICs:\n\tdef __init__(self):\n\t\tself.Template = 0\n\t\tself.PRC ='Not Allow'\n\t\t# Double price information\n\t\t# Format:\n\t\t# [SRCRowNum,SRCRowColumn,LayoutNum,FormatColumn]\n\t\tself.DPrice = []\n\t\t# Single price information\n\t\t# Format:\n\t\t# [SRCRowNum,SRCRowColumn,LayoutNum,FormatColumn]\n\t\t# If blank then insert None\n\t\tself.SingleFid = []\n\t\t# MarketRule information:\n\t\t# Format:\n\t\t# [StrategyIDColumn,SubRuleName,SubRuleColumn,CalendarColumn]\n\t\tself.MarketRule = []\n\t\t# Dynamic FidList:\n\t\t# Format:\n\t\t# [DoublePrice,Single1,Single2,...]\n\t\t# Doesn't filter out the same name FID or FIDs not in the template.\n\t\tself.FidList = []\n\t\t# StaticFids End Column\n\t\tself.StaticEnd = 0\n\t\t# PriceFid Dict:\n\t\t# key: RowNum\n\t\t# Value: list of Price FID index in SingleFID\n\t\t# E.g: {10:[0,3], 11:[1,4]}\n\t\tself.PriceFid = {}\n\t\t# Price Fid Condition String\n\t\tself.PriceString = {}\n\n","sub_path":"RICs.py","file_name":"RICs.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"234583192","text":"import json\nimport logging\n\nfrom django.http import JsonResponse\nfrom django.views.decorators.http import require_http_methods\n\nfrom ..models import Film\n\n# Get an instance of a logger\nlogger = logging.getLogger(\"django\")\n\n\n@require_http_methods([\"POST\"])\ndef datatable_search(request):\n \"\"\" Search films from db \"\"\"\n\n args = json.loads(\n request.body) if request.method == 'POST' and request.body else {}\n logger.debug(\"Input args: %s\", args)\n\n data = Film.datatable_search(args)\n\n films = []\n for film in data['films']:\n film_dict = film.row2dict()\n film_dict['language'] = film.language.row2dict()\n film_dict['categories'] = [category.row2dict()\n for category in film.categories.all()]\n film_dict['actors'] = [actor.row2dict()\n for actor in film.actors.all()]\n films.append(film_dict)\n\n response = {\n 'fetch_id': args.get('fetch_id'),\n 'records_total': data['records_total'],\n 'records_filtered': data['records_filtered'],\n 'data': films,\n }\n\n return JsonResponse(response, json_dumps_params={'indent': 2})\n","sub_path":"api/controllers/film.py","file_name":"film.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"89226720","text":"import discord\nfrom discord.ext import commands\n\nclient = discord.Client()\ntoken = open(\"token.txt\", \"r\").read()\n\n@client.event\nasync def on_ready():\n print(f\"We are live as {client.user}\")\n\n@client.event\nasync def on_message(msg):\n channelName = str(msg.channel)\n\n if channelName != \"commands\" or channelName != \"bot-construction\":\n return\n\n cmd = msg.content.lower()\n\n switchcase = {\n\n \"twitch()\": await msg.channel.send(\"Go Follow Melkeydev over at https://www.twitch.tv/melkeydev\"),\n\n \"test()\": await msg.channel.send(\"Test worked you didnt break it yet\"),\n\n \"schedule()\": await msg.channel.send(\"Melkey streams start on Mondays, Wednesdays, and Fridays at 9PM EST\"),\n\n \"project()\": await msg.channel.send(\"Melkey is working on a NBA app written in react to search, and compare player stats!\"),\n\n \"pow()\": await msg.channel.send(\"The pow is a sacred technique practice by the ancient tribes of Konoha.\"),\n\n \"crash()\": await msg.channel.send(\"Nice try I am impossible to crash\"),\n\n \"dot()\": await msg.channel.send(\"Check out my dotfiles at https://github.com/Amokstakov/NvimConfig\")\n\n }\n return switchcase.get(cmd, None)\nif __name__ == \"__main__\":\n client.run(token)\nelse:\n print('Do not import.')\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"70712837","text":"import copy\n\nclass Action:\n def __init__(self, pos, text, from_version, to_version):\n self.pos = pos\n self.text = text\n self.from_version = from_version\n self.to_version = to_version\n\n @staticmethod\n def _insert(text, text_diff, pos):\n if pos <= len(text):\n return text[0:pos] + str(text_diff) + text[pos:]\n raise ValueError\n\n @staticmethod\n def _replace(text, text_diff, pos):\n replace_length = len(str(text_diff))\n return text[:pos] + str(text_diff) + text[pos+replace_length:]\n\n\nclass TextHistory:\n DEFAULT_VERSION = 0\n BUFFER = dict()\n act_buff = []\n\n def __init__(self, text=None, version=0):\n self._text = text or ''\n self._version = version\n self.BUFFER[self._version] = self._text\n\n @property\n def text(self):\n return self._text\n\n @property\n def version(self):\n return self._version\n\n def _writing_buffer(self, diff, pos, method):\n self.BUFFER[self._version] = {\n 'text': self.text,\n 'diff': diff,\n 'pos': pos,\n 'method': method\n }\n return self.BUFFER\n\n def _write_act_buff(self, act):\n self.act_buff.append(act)\n \n def insert(self, diff_text, pos=None):\n if pos is None:\n pos = len(self._text)\n if pos > len(self._text) or pos < 0:\n raise ValueError\n action = InsertAction(pos=pos, text=diff_text, from_version=self.version, to_version=self.update_version())\n self.action(action)\n self._writing_buffer(diff_text, pos, 'insert')\n return self._version\n\n def replace(self, diff_text, pos=None):\n if pos is None:\n pos = len(self._text)\n if pos > len(self._text) or pos < 0:\n raise ValueError\n action = ReplaceAction(pos=pos, text=diff_text, from_version=self.version, to_version=self.update_version())\n self.action(action)\n self._writing_buffer(diff_text, pos, 'replace')\n return self._version\n\n def delete(self, pos=None, length=0):\n if pos is None:\n pos = len(self._text)\n print(f'pos {pos}, length {length}')\n if pos > len(self._text) or (pos + length) > len(self._text) or pos < 0:\n raise ValueError\n action = DeleteAction(pos=pos, length=length, from_version=self.version, to_version=self.update_version())\n self.action(action)\n self._writing_buffer(pos=pos, diff=length, method='delete')\n return self._version\n\n def update_version(self, to_version=0):\n to_version = to_version or self._version\n if to_version > self._version:\n return to_version\n elif to_version == self._version:\n return to_version + 1\n else:\n raise ValueError\n return self._version\n\n def action(self, act):\n if act.to_version <= act.from_version:\n raise ValueError\n\n self._text = act.apply(self.text)\n self._write_act_buff(act)\n self._version = self.update_version(act.to_version)\n return self._version\n\n def optimization_act_buf(self):\n print(f'before optimization:\\n{self.act_buff}')\n # Оптимизация работает только для объектов InsertAction and ReplaceAction\n # Работает так: если есть два однотипных экшна подряд, к примеру:\n # h.insert('a')\n # h.insert('bc')\n # то их можно представить одним h.insert('abc')\n i = 0\n g = 0\n action_list = copy.copy(self.act_buff)\n for i in range(0, len(self.act_buff)):\n if i < len(self.act_buff):\n act_type = self.act_buff[i].__class__\n for g in range(i + 1, len(self.act_buff)):\n if g < len(self.act_buff):\n if isinstance(self.act_buff[g], act_type) and \\\n (self.act_buff[g].pos + len(self.act_buff[g].text)) == \\\n (self.act_buff[i].pos + len(self.act_buff[i].text) + \\\n len(self.act_buff[g].text)):\n action_list[i].text = self.act_buff[i].text + self.act_buff[g].text\n action_list[i].to_version = self.act_buff[g].to_version\n action_list.pop(g)\n else:\n i = g\n break\n else:\n break\n g += 1\n i += 1\n print(f'after optimization:\\n{action_list}')\n return action_list\n\n # Оптимизации________________________________________________\n\n def get_actions(self, from_version=0, to_version=None):\n if to_version is None:\n to_version = len(self.act_buff)\n if not (0<= from_version <= to_version <= len(self.act_buff)):\n raise ValueError\n self.act_buff = self.optimization_act_buf()\n return self.act_buff[from_version:to_version]\n\nclass InsertAction(Action):\n def apply(self, text):\n return self._insert(text, self.text, self.pos)\n\n\nclass ReplaceAction(Action):\n def apply(self, text):\n return self._replace(text, self.text, self.pos)\n\n\nclass DeleteAction(Action):\n def __init__(self, pos, length, from_version, to_version):\n self.pos = pos\n self.length = length\n self.from_version = from_version\n self.to_version = to_version\n\n @staticmethod\n def _delete(text, length, pos):\n return text[:pos] + text[pos + length:]\n\n def apply(self, text):\n return self._delete(text, self.length, self.pos)\n\n\ndef main():\n h = TextHistory()\n h.insert('a')\n h.insert('bc')\n h.replace('B', pos=1)\n h.delete(pos=0, length=1)\n\n actions = h.get_actions(1)\n print(actions)\n print(len(actions))\n print('_____________')\n\n insert, replace, delete = actions\n # insert\n print(insert.from_version)\n print(insert.to_version)\n print(insert.text)\n print(insert.pos)\n print('_____________')\n # replace\n print(replace.from_version)\n print(replace.to_version)\n print(replace.text)\n print(replace.pos)\n print('_____________')\n # delete\n print(delete.from_version)\n print(delete.to_version)\n print(delete.pos)\n print(delete.length)\n\n\n\n\n\nif __name__==\"__main__\":\n main()","sub_path":"009_text_history/text_history.py","file_name":"text_history.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"584897095","text":"import datetime, json, logging, uuid\nfrom . import LANGUAGES, RE_CHALLENGE_ID, RE_USER_ID\nfrom .StorageHelper import StorageKeys, get_redis, wait_for_redis\n\n# -------------------------------------------------------------------\n\n@wait_for_redis\ndef CreateSubmission(lang, user_id, challenge_id, code, simulation=None):\n\t# Language\n\tlang = lang.strip()\n\tif not lang in LANGUAGES:\n\t\tlogging.error('Language is invalid')\n\t\treturn None\n\n\t# User\n\tuser_id = user_id.strip()\n\tif not RE_USER_ID.match(user_id):\n\t\tlogging.error('User is invalid')\n\t\treturn None\n\tuser = get_redis().hget(StorageKeys.Users, user_id)\n\tif not user:\n\t\tlogging.error('User is Unknown')\n\t\treturn None\n\n\t# Challenge\n\tchallenge_id = challenge_id.strip()\n\tif not RE_CHALLENGE_ID.match(challenge_id):\n\t\tlogging.error('Challenge is invalid')\n\t\treturn None\n\tfrom .ChallengeHelper import LoadChallenge\n\tif not LoadChallenge(challenge_id):\n\t\tlogging.error('Challenge is unknown')\n\t\treturn None\n\n\t# Code\n\tcode = code.replace('\\r', '')\n\tif not code:\n\t\tlogging.error('Code is invalid')\n\t\treturn None\n\n\t# Execute\n\tsubmission_id = str(uuid.uuid4())\n\tsubmission = {\n\t\t'challenge_id': challenge_id,\n\t\t'code': code,\n\t\t'id': submission_id,\n\t\t'lang': lang,\n\t\t'stamp': datetime.datetime.utcnow().timestamp(),\n\t\t'user_id': user_id\n\t}\n\tif simulation != None:\n\t\tif not isinstance(simulation, int):\n\t\t\tlogging.error('Simulation is invalid: %s', simulation)\n\t\t\treturn None\n\t\tsubmission['simulation'] = simulation\n\n\tpipe = get_redis().pipeline()\n\tpipe.hset(StorageKeys.Submissions, submission_id, json.dumps(submission))\n\tpipe.lpush(StorageKeys.SubmissionsQueue, submission_id)\n\tpipe.execute()\n\n\treturn submission\n\n# -------------------------------------------------------------------\n\n@wait_for_redis\ndef LoadSubmissions():\n\treturn [ json.loads(submission) for submission_id, submission in get_redis().hgetall(StorageKeys.Submissions).items() ]\n\n# -------------------------------------------------------------------\n\n@wait_for_redis\ndef LoadSubmission(submission_id):\n\tsubmission = get_redis().hget(StorageKeys.Submissions, submission_id)\n\treturn json.loads(submission) if submission else None\n\n# -------------------------------------------------------------------\n\n@wait_for_redis\ndef WaitSubmission():\n\tlogging.info('Wait submission')\n\tsubmission_id = get_redis().brpoplpush(StorageKeys.SubmissionsQueue, StorageKeys.SubmissionsQueueWIP, 0)\n\tlogging.info('Load submission %s', submission_id)\n\treturn json.loads(get_redis().hget(StorageKeys.Submissions, submission_id))\n\n# -------------------------------------------------------------------\n","sub_path":"app/helpers/SubmissionHelper.py","file_name":"SubmissionHelper.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"227816894","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport re\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef add_model_freezing_configs(_C):\n _C.MODEL.FROZEN_LAYER_REG_EXP = []\n\n\ndef set_requires_grad(model, reg_exps, value):\n total_num_parameters = 0\n unmatched_parameters = []\n unmatched_parameter_names = []\n matched_parameters = []\n matched_parameter_names = []\n for name, parameter in model.named_parameters():\n total_num_parameters += 1\n matched = False\n for frozen_layers_regex in reg_exps:\n if re.match(frozen_layers_regex, name):\n matched = True\n parameter.requires_grad = value\n matched_parameter_names.append(name)\n matched_parameters.append(parameter)\n break\n if not matched:\n unmatched_parameter_names.append(name)\n unmatched_parameters.append(parameter)\n logger.info(\"Matched layers (require_grad={}): {}\".format(\n value, matched_parameter_names))\n logger.info(\"Unmatched layers: {}\".format(unmatched_parameter_names))\n return matched_parameter_names, unmatched_parameter_names\n","sub_path":"d2go/modeling/model_freezing_utils.py","file_name":"model_freezing_utils.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"375750666","text":"\n\"\"\"\nO(n^2) implementation of suffix tree construction\n\"\"\"\nimport collections\n\nclass SuffixTreeNode:\n \"\"\"\n Node for the suffix tree.\n Instead of storing substrings in edges, store them\n in nodes instead.\n\n :param length: The length of the text in the node\n :param end: The ending index of the text in the node\n :param children: List of SuffixTreeNode children\n :param leaf: The suffix for which this is a leaf of. -1\n if not a leaf\n \"\"\"\n\n def __init__(self, length=0, end=0, children=[], leaf = -1):\n self.length = length\n self.end = end\n self.children = [x for x in children]\n self.leaf = leaf\n \n def add_child(self, child):\n \"\"\"\n Add a child to this node\n\n :param child: The child node to add\n \"\"\"\n self.children.append(child)\n\n def get_text(self, text):\n \"\"\"\n Return the text stored in the node\n\n :param text: The full text that end and length refer to\n :return: The substring in the node\n \"\"\"\n return text[self.end - self.length : self.end]\n\nclass SuffixTree:\n \"\"\"\n Create a Suffix Tree from the given text\n\n :param text: Text to create the suffix tree from\n \"\"\"\n\n def __init__(self, text, suffix=True):\n self.text = text\n self.__suffix = suffix\n self.__create_tree(text)\n\n def search(self, pattern):\n \"\"\"\n Search for the pattern in the suffix tree\n\n :param pattern: The pattern to search for\n :return: [start indices]\n \"\"\"\n node = self.root\n # Start index of unfound items in pattern\n index = 0\n while index < len(pattern):\n valid = False\n for child in node.children:\n if child.leaf == -1:\n start = child.end - child.length\n length = min(child.length, len(pattern) - index)\n child_text = self.text[start : start+length]\n pattern_text = pattern[index : index+length]\n if child_text == pattern_text:\n valid = True\n index = index + length\n node = child\n break\n if valid == False:\n return []\n return self.__leaves(node)\n\n def __leaves(self, node):\n \"\"\"\n Get the leaf nodes of the current node\n\n :param node: The node to get the leaves of\n :return: [leaf node indices]\n \"\"\"\n leaves = []\n queue = collections.deque()\n queue.append(node)\n while len(queue) > 0:\n node = queue.pop()\n if node.leaf != -1:\n leaves.append(node.leaf)\n for child in node.children:\n queue.append(child)\n leaves.sort()\n return leaves\n\n def __create_tree(self, text):\n \"\"\"\n Create the suffix tree\n\n :param text: Text to create the suffix tree from\n \"\"\"\n keyword = self.__create_keyword(text)\n if self.__suffix:\n self.root = self.__condense_keyword(keyword)\n else:\n self.root = keyword\n\n def __create_keyword(self, text):\n \"\"\"\n Create the keyword tree\n\n :param text: Text to create the keyword tree from\n :return: The root of the created keyword tree\n \"\"\"\n # Create the keyword tree for all suffixes\n temp_root = SuffixTreeNode()\n for i in range(len(text)):\n self.__add_to_keyword(temp_root, i)\n return temp_root\n\n def __add_to_keyword(self, root, index):\n \"\"\"\n Add the given suffix to the tree\n\n :param root: The root of the tree\n :param index: The starting index of the suffix to add\n \"\"\"\n node = root\n for i in range(index, len(self.text)):\n cont = True\n for child in node.children:\n if child.leaf == -1:\n if child.get_text(self.text) == self.text[i]:\n node = child\n cont = False\n break\n if cont:\n new_node = SuffixTreeNode(1, i+1)\n node.add_child(new_node)\n node = new_node\n new_node = SuffixTreeNode(leaf=index)\n node.add_child(new_node)\n\n def __condense_keyword(self, keyword):\n \"\"\"\n Condense the keyword tree into a suffix tree\n\n :param keyword: The keyword tree \n \"\"\"\n queue = collections.deque()\n for child in keyword.children:\n queue.append(child)\n while len(queue) > 0:\n node = queue.popleft()\n if node.leaf == -1:\n while len(node.children) == 1:\n child = node.children[0]\n if child.leaf == -1:\n node.length = node.length + child.length\n node.end = child.end\n node.children = child.children\n else:\n break\n for child in node.children:\n queue.append(child)\n return keyword\n\n","sub_path":"suffix_tree.py","file_name":"suffix_tree.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619464472","text":"#!/usr/bin/env python3\n\n# Copyright © 2021 Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences, Potsdam, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n\"\"\"\nUnit tests for modelprop.\n\"\"\"\n\nimport unittest\n\nimport modelprop\n\nfrom test_cmd import *\n\n\nclass TestAll(unittest.TestCase):\n \"\"\"\n Unit test class.\n \"\"\"\n\n def test_get_supported_schemas(self):\n \"\"\"\n Extracts which schemas are supported.\n :return: None\n \"\"\"\n supported_schemas = modelprop.get_supported_schemas()\n\n assumed_schemas = [\n \"HAZUS_v1.0\",\n \"SARA_v1.0\",\n \"SUPPASRI2013_v2.0\",\n \"Mavrouli_et_al_2014\",\n \"Torres_Corredor_et_al_2017\",\n \"Medina_2019\",\n ]\n\n self.assertTrue(supported_schemas)\n\n self.assertEqual(len(assumed_schemas), len(supported_schemas))\n\n for schema in assumed_schemas:\n self.assertIn(schema, supported_schemas)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"293370860","text":"\n# ### 수작업으로 만들었음...\n# decBook = {\n# \"2\": \"H\",\n# \"3\": \"e\",\n# \"1\": \"l\",\n# \"4\": \"o\",\n# \"9\": \"W\"\n# \"8\": \"r\"\n# \"7\": \"d\"\n# }\n\n\n# 자동으로 decBook을 만드는 함수...\ndef makeDecCodeBook(encBook):\n decBook = {}\n for k in encBook:\n val = encBook[k]\n decBook[val] = k\n return decBook\n\n## encryption 과정\n## input : msg, encBook\n## output : output\n\ndef encWithCodeBook(msg, encBook):\n output = \"\"\n for m in msg:\n if m in encBook: # 만약 msg 의 값 한개 씩 읽어와서 encBook 에 있으면 그것을 변환해서 output 에 붙여준다.\n output += encBook[m]\n else:\n output += m\n return output\n\ndef encWithCodeBook2(msg, encBook):\n for m in msg:\n if m in encBook: # 다른 방식의 인코딩\n msg = msg.replace(m, encBook[m])\n else:\n msg += m\n return msg\n\n\n\n## decryption 과정\n# input : output, decBook\n# output : PlainText\n\ndef decWithCodeBook(output, decBook):\n PlainText = \"\"\n for m in output:\n if m in decBook:\n PlainText += decBook[m]\n else:\n PlainText += m\n return PlainText\n\ndef decWithCodeBook2(output, decBook):\n for m in output:\n if m in decBook:\n output = output.replace(m, decBook[m])\n else:\n output += m\n return output\n\n\ndef encdecWithCodeBook(input, codeBook): ## encode decode 과정을 한번에 합친 함수\n for m in input:\n if m in codeBook:\n input = input.replace(m, codeBook[m])\n else:\n input += m\n return input\n\n\n# main...\n\nencBook = {\n \"H\": \"2\",\n \"e\": \"3\",\n \"l\": \"1\",\n \"o\": \"4\",\n \"W\": \"9\",\n \"r\": \"8\",\n \"d\": \"7\"\n}\n\ndecBook = makeDecCodeBook(encBook)\nprint(decBook)\n\nmsg = \"Hello World\"\n\ncipher = encWithCodeBook(msg, encBook)\nprint(cipher)\n\ncipher2 = encWithCodeBook2(msg, encBook)\nprint(cipher2)\n\nplaintext = decWithCodeBook(cipher, decBook)\nprint(plaintext)\n\nplaintext2 = decWithCodeBook2(cipher2, decBook)\nprint(plaintext2)\n\n\ncipher3 = encdecWithCodeBook(msg, encBook)\nprint(cipher3)\n\nplaintext3 = encdecWithCodeBook(cipher3, decBook)\nprint(plaintext3)\n","sub_path":"SecurityPythonCode/SecuPro/CodeBookCipher.py","file_name":"CodeBookCipher.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"359483240","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import (absolute_import, division, print_function)\n\nimport os\nimport sys\nimport warnings\n\nimport ansible.constants\nimport ansible.errors\nimport ansible.utils\nimport pytest\nfrom pprint import pprint\nfrom ibm_zos_ims.tests.functional.module_utils.ims_test_gen_utils import DBDInputParameters as ip\n\n__metaclass__ = type\n\nGEN_SUCCESS_MSG = 'DBDGEN execution was successful.'\nBATCH_SUCCESS_RETURN_TEXT = 'success'\n\n\ndef test_ims_dbd_gen_sample(ansible_zos_module):\n hosts = ansible_zos_module\n source = ip.SOURCE\n\n dest = ip.DESTINATION\n sys_lib = ip.SYSLIB\n results = hosts.all.ims_dbd_gen(src=source, location=\"DATA_SET\", replace=True, member_list=['DEDBJN21', 'DEDBJN21'], dest=dest, sys_lib=sys_lib)\n\n for result in results.contacted.values():\n pprint(result)\n assert result['changed']\n # Check return code for array of output for each source\n assert result['rc'] == 0\n\n # Check for success message (if we remove return codes)\n assert result['msg'] == GEN_SUCCESS_MSG\n\n\ndef test_ims_dbd_gen_sample_batch(ansible_zos_module):\n hosts = ansible_zos_module\n source = ip.SOURCE\n dest = ip.DESTINATION\n sys_lib = ip.SYSLIB\n batch_list = [{\n 'src': source,\n 'location': 'DATA_SET',\n 'replace': True,\n 'member_list': 'DEDBJN21'}]\n results = hosts.all.ims_dbd_gen(batch=batch_list, dest=dest, sys_lib=sys_lib)\n\n for result in results.contacted.values():\n pprint(result)\n assert result['changed']\n # Check return code for array of output for each source\n assert result['rc'] == 0\n # Check for success message (if we remove return codes)\n assert result['msg'] == GEN_SUCCESS_MSG\n\n for src_result in result['batch_result']:\n assert src_result['return_text'] == BATCH_SUCCESS_RETURN_TEXT\n","sub_path":"tests/functional/modules/ims_dbd_gen/test_ims_dbd_gen_sample2.py","file_name":"test_ims_dbd_gen_sample2.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"179505175","text":"#!/usr/local/bin/python3.6\n#-*-encoding:utf-8-*-\n#题目:\n#作者:luohu\n#时间:2018-09\n#目的:\nfrom tkinter import *\nfrom tkinter.messagebox import showinfo\ndef reply(name):\n\tshowinfo(title=\"回复\",message=\"Hello %s!\" %name)\n\ntop = Tk()\ntop.title(\"天龙八部\")\ntop.iconbitmap(\"haha.svg\")\n\n#Label控件:Label 控件用以显示文字和图片. Label 通常被用来展示信息, 而非与用户交互. \nLabel(top,text=\"请输出你的名字:\").pack(side=TOP)\n#Entry 是 Tkinter 用来接收字符串等输入的控件. 该控件允许用户输入一行文字.\n\nent = Entry(top)\nent.pack(side=TOP)\nbtn = Button(top,text=\"提交\",command=(lambda:reply(ent.get())))\nbtn.pack(side=LEFT)\n\ntop.mainloop()\n\n","sub_path":"python_program/01.Preview/tkinter103.py","file_name":"tkinter103.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"426878609","text":"started = False\r\nname=input(\"Enter your name: \")\r\nprint(f\"Hii {name} let's play a game\")\r\ncommand = \"\"\r\nwhile command != \"quit\":\r\n input_command= input(\"> \")\r\n if input_command.upper() == \"HELP\":\r\n print('''\r\nstart - to start the car\r\nstop - to stop the car\r\nquit - to exit\r\n ''')\r\n elif input_command.upper() == \"START\":\r\n if started :\r\n print(\"Car is alreay started ... what are doing\")\r\n else :\r\n started = True\r\n print(\"Car started... Ready to go!\")\r\n elif input_command.upper() == \"STOP\" :\r\n if not started:\r\n print(\"you already stop ... what are you doing\")\r\n else :\r\n started = False\r\n print(\"Car stopped\")\r\n\r\n\r\n elif input_command.upper() == \"QUIT\" :\r\n exit_command = input('''\r\ndo u want to quit \r\n (y)es and (N)o\r\n > ''' ).lower()\r\n if exit_command == \"y\" :\r\n command = 'quit'\r\n else :\r\n print(\"I don't understand that ...\")\r\n\r\n\r\n\r\n","sub_path":"Python_code/Game_start.py","file_name":"Game_start.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"462036079","text":"#!/c/Python35/python.exe\r\n\r\nimport sys\r\nimport os\r\nimport shutil\r\n\r\ndef main(argv):\r\n\tscript_path = str(os.path.dirname(os.path.abspath(__file__)))\r\n\r\n\tif len(argv) == 0:\r\n\t\tprint(\"Script Usage: post-build-event.py \\\"$(TargetDir)\\\"\")\r\n\telse:\r\n\t\ttarget_dir = argv[0]\r\n\t\t\r\n\t\tprint(\"Post-Buid Event script path:\", script_path)\r\n\t\tprint(\"Post-Buid Event target path:\", target_dir)\r\n\t\t\r\n\t\tif not os.path.exists(target_dir):\r\n\t\t\tprint(\"The specified target directory was not found.\")\r\n\t\t\tsys.exit(1)\r\n\t\tcopy_dependencies(script_path, target_dir)\r\n\r\ndef copy_dependencies(root_path, target_dir):\r\n\tif not root_path.endswith('\\\\'):\r\n\t\troot_path += '\\\\'\r\n\r\n\tprint(\"Copying libcurl.dll...\")\r\n\tshutil.copy2(root_path + \"..\\\\..\\\\curl\\\\lib\\\\Debug\\\\libcurl.dll\", target_dir)\r\n\tprint(\"Dependencies copied.\")\r\n\r\nif __name__ == \"__main__\":\r\n\tmain(sys.argv[1:])\r\n","sub_path":"books/cpp-tdd/TestDoubles/post-build-event.py","file_name":"post-build-event.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"68133404","text":"# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\n# ALLOWED_HOSTS must be correct in production!\n# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts\nALLOWED_HOSTS = ['*']\n\n# Databases\n#DATABASES['default']['NAME'] = 'wcs'\n#DATABASES['default']['USER'] = 'wcs'\n#DATABASES['default']['PASSWORD'] = 'wcspass'\n#DATABASES['default']['HOST'] = 'db'\n#DATABASES['default']['PORT'] = '5432'\n\n# Zone\nLANGUAGE_CODE = 'fr-fr'\nTIME_ZONE = 'Europe/Paris'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse',\n },\n 'require_debug_true': {\n '()': 'django.utils.log.RequireDebugTrue',\n },\n },\n 'formatters': {\n 'simple': {\n 'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s',\n 'datefmt': '%d/%b/%Y %H:%M:%S'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'filters': ['require_debug_true'],\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n },\n 'loggers': {\n\t'':{\n 'handlers': ['console'],\n 'level': 'INFO',\n 'disabled': False\n },\n },\n}\n\n# Email configuration\n# EMAIL_SUBJECT_PREFIX = '[combo] '\n# SERVER_EMAIL = 'root@combo.example.org'\n# DEFAULT_FROM_EMAIL = 'webmaster@combo.example.org'\n\n# SMTP configuration\nEMAIL_HOST = 'smtp'\n# EMAIL_HOST_USER = ''\n# EMAIL_HOST_PASSWORD = ''\nEMAIL_PORT = 1025\n\n# HTTPS Security\nCSRF_COOKIE_SECURE = True\nSESSION_COOKIE_SECURE = True\n\n","sub_path":"wcs/wcs.settings.py","file_name":"wcs.settings.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"154851439","text":"import torch\nfrom torch import nn\n\nfrom CLS_GM.feature_extractor import FeatureExtractor\n\n\nclass Net_Class(torch.nn.Module):\n def __init__(self):\n super(Net_Class, self).__init__()\n num_class = 20\n self.feature_extractor = FeatureExtractor()\n self.classifier = nn.Sequential(\n nn.Linear(2048, 1024),\n torch.nn.Dropout(p=0.5),\n nn.ReLU(),\n nn.Linear(1024, num_class)\n )\n\n def forward(\n self,\n images,\n points,\n graphs,\n n_points,\n perm_mats,\n n_label,\n c_label,\n visualize_flag=False,\n visualization_params=None\n ):\n _, global_list = self.feature_extractor(images,\n points,\n graphs,\n n_points,\n perm_mats,\n visualize_flag,\n visualization_params)\n return [self.classifier(global_feat) for global_feat in global_list]\n","sub_path":"CLS_GM/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"536365374","text":"#! /usr/bin/python\n# -*- coding: utf8 -*-\nimport time\nimport tensorlayer as tl\nimport progressbar\nimport zipfile\nimport os\nimport urllib.request\n\npbar = None\n\ndef show_progress(block_num, block_size, total_size):\n global pbar\n if pbar is None:\n pbar = progressbar.ProgressBar(maxval=total_size)\n\n downloaded = block_num * block_size\n if downloaded < total_size:\n pbar.update(downloaded)\n else:\n pbar.finish()\n pbar = None\n\ndef download_vgg():\n url = \"https://www.dropbox.com/s/7mmianmwcj2qyl5/vgg16.npy?dl=1\"\n urllib.request.urlretrieve(url, 'vgg/vgg16.npy', show_progress)\n\ndef download_models():\n url = \"https://www.dropbox.com/s/f51f795qq7of9rt/Reproducible%20challenge.zip?dl=1\"\n urllib.request.urlretrieve(url, 'Precomputed_weights.zip', show_progress)\n print(\"Finished Download. Starting unzipping of the file:\")\n with zipfile.ZipFile(\"Precomputed_weights.zip\",\"r\") as zip_ref:\n zip_ref.extractall(\"Precomputed_weights\")\n os.remove(\"Precomputed_weights.zip\")\n print(\"Finished Unzipping. Weights of the model located in Precomputed_weights folder\")\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--mode', type=str, default='vgg', help='gdepth')\n args = parser.parse_args()\n\n tl.global_flag['mode'] = args.mode\n\n if tl.global_flag['mode'] == 'vgg':\n print(\"Downloading vgg-16 weights\")\n download_vgg()\n elif tl.global_flag['mode'] == 'weights':\n print(\"Downloading precomputed weights for each model\")\n download_models()\n #pass\n else:\n raise Exception(\"Unknow --mode\")\n","sub_path":"download_weights.py","file_name":"download_weights.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"545853646","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\":Mod: rules\n\n:Synopsis:\n\n:Author:\n servilla\n\n:Created:\n 6/4/18\n\"\"\"\nimport daiquiri\n\nfrom eml2_1_1.exceptions import MPLRuleError\nfrom mom.model import Node\n\n\nlogger = daiquiri.getLogger('rules: ' + __name__)\n\nREQUIRED = True\nOPTIONAL = False\nINFINITY = None\n\n\ndef access_rule(node: Node):\n rules = [\n ['allow', 'deny', 1, INFINITY]\n ]\n process_rules(rules, node)\n attributes = {\n 'id': OPTIONAL,\n 'system': OPTIONAL,\n 'scope': OPTIONAL,\n 'order': OPTIONAL,\n 'authSystem': REQUIRED\n }\n process_attributes(attributes, node)\n if 'order' in node.attributes:\n allowed = ['allowFirst', 'denyFirst']\n if node.attributes['order'] not in allowed:\n msg = '\"{0}:order\" attribute must be one of \"{1}\"'.format(node.rank, allowed)\n raise MPLRuleError(msg)\n\n\ndef additional_metadata_rule(node: Node):\n rules = [\n ['describes', 0, INFINITY],\n ['metadata', 1, 1]\n ]\n process_rules(rules, node)\n attributes = {\n 'id': OPTIONAL\n }\n process_attributes(attributes, node)\n\n\ndef allow_rule(node: Node):\n rules = [\n ['principal', 1, INFINITY],\n ['permission', 1, INFINITY]\n ]\n process_rules(rules, node)\n\n\ndef any_name_rule(node: Node):\n rules = [\n ['value', 0, INFINITY]\n ]\n process_rules(rules, node)\n attributes = {\n 'lang': OPTIONAL\n }\n process_attributes(attributes, node)\n if node.content is not None and type(node.content) is not str:\n msg = 'Node \"{0}\" content should be type string, not \"{1}\"'.format(node.rank, type(node.content))\n raise MPLRuleError(msg)\n if len(node.children) == 0 and node.content is None:\n msg = 'Node \"{0}\" content should not be empty'.format(node.rank)\n raise MPLRuleError(msg)\n\ndef dataset_rule(node: Node):\n pass\n\n\ndef deny_rule(node: Node):\n rules = [\n ['principal', 1, INFINITY],\n ['permission', 1, INFINITY]\n ]\n process_rules(rules, node)\n\n\ndef eml_rule(node: Node):\n rules = [\n ['access', 0, 1],\n ['dataset', 'citation', 'software', 'protocol', 1, 1],\n ['additionalMetadata', 0, INFINITY]\n ]\n process_rules(rules, node)\n attributes = {\n 'packageId': REQUIRED,\n 'system': REQUIRED,\n 'scope': OPTIONAL,\n 'lang': OPTIONAL\n }\n process_attributes(attributes, node)\n\n\ndef individual_name_rule(node: Node):\n rules = [\n ['salutation', 0, INFINITY],\n ['givenName', 0, INFINITY],\n ['surName', 1, 1]\n ]\n process_rules(rules, node)\n\n\ndef metadata_rule(node: Node):\n if len(node.children) != 0:\n msg = 'Node \"{0}\" should not have children'.format(node.rank)\n raise MPLRuleError(msg)\n if type(node.content) is not str:\n msg = 'Node \"{0}\" content should be type string, not \"{1}\"'.format(node.rank, type(node.content))\n raise MPLRuleError(msg)\n\n\ndef permission_rule(node: Node):\n if len(node.children) != 0:\n msg = 'Node \"{0}\" should not have children'.format(node.rank)\n raise MPLRuleError(msg)\n allowed = ['read', 'write', 'changePermission', 'all']\n if node.content not in allowed:\n msg = 'Node \"{0}\" content should be one of \"{1}\", not \"{2}\"'.format(node.rank, allowed, node.content)\n raise MPLRuleError(msg)\n\n\ndef principal_rule(node: Node):\n if len(node.children) != 0:\n msg = 'Node \"{0}\" should not have children'.format(node.rank)\n raise MPLRuleError(msg)\n if type(node.content) is not str:\n msg = 'Node content should be type string, not \"{0}\"'.format(type(node.content))\n raise MPLRuleError(msg)\n\n\ndef responsible_party_rule(node: Node):\n rules = [\n ['individualName', 'organizationName', 'positionName', 1, INFINITY],\n ['address', 0, INFINITY],\n ['phone', 0, INFINITY],\n ['electronicMailAddress', 0, INFINITY],\n ['onlineUrl', 0, INFINITY],\n ['userId', 0, INFINITY]\n ]\n process_rules(rules, node)\n attributes = {\n 'id': OPTIONAL,\n 'system': OPTIONAL,\n 'scope': OPTIONAL\n }\n process_attributes(attributes, node)\n\n\ndef title_rule(node: Node):\n if node.content is not None and type(node.content) is not str:\n msg = 'Node \"{0}\" content should be type string, not \"{1}\"'.format(node.rank, type(node.content))\n raise MPLRuleError(msg)\n rules = [\n ['value', 0, INFINITY]\n ]\n process_rules(rules, node)\n attributes = {\n 'lang': OPTIONAL\n }\n process_attributes(attributes, node)\n\n\ndef value_rule(node: Node):\n if node.content is None:\n msg = 'Node \"{0}\" content cannot be empty'.format(node.rank)\n raise MPLRuleError(msg)\n if type(node.content) is not str:\n msg = 'Node \"{0}\" content should be type string, not \"{1}\"'.format(node.rank, type(node.content))\n raise MPLRuleError(msg)\n attributes = {\n 'xml:lang': REQUIRED,\n }\n process_attributes(attributes, node)\n\n\ndef process_rules(rules, node: Node):\n i = 0\n max_i = len(node.children)\n for rule in rules:\n rank = rule[:-2]\n min = rule[-2]\n max = rule[-1]\n cnt = 0\n while i < max_i:\n child_rank = node.children[i].rank\n if child_rank in rank:\n cnt += 1\n if max is not INFINITY and cnt > max:\n msg = 'Maximum occurrence of \"{0}\" exceeded for \"{1}\"'.format(rank, node.rank)\n raise MPLRuleError(msg)\n i += 1\n else: break\n if cnt < min:\n msg = 'Minimum occurrence of \"{0}\" not met for \"{1}\"'.format(rank, node.rank)\n raise MPLRuleError(msg)\n if i < max_i:\n child_rank = node.children[i].rank\n msg = 'Child \"{0}\" not allowed for \"{1}\"'.format(child_rank, node.rank)\n raise MPLRuleError(msg)\n\n\ndef process_attributes(attributes, node: Node):\n for attribute in attributes:\n required = attributes[attribute]\n if required and attribute not in node.attributes:\n msg = '\"{0}\" is a required attribute of node \"{1}\"'.format(attribute, node.rank)\n raise MPLRuleError(msg)\n for attribute in node.attributes:\n if attribute not in attributes:\n msg = '\"{0}\" is not a recognized attributes of node \"{1}\"'.format(attribute, node.rank)\n raise MPLRuleError(msg)\n\n\n\nrules = {\n 'access': access_rule,\n 'additionalMetadata': additional_metadata_rule,\n 'allow': allow_rule,\n 'contact': responsible_party_rule,\n 'creator': responsible_party_rule,\n 'dataset': dataset_rule,\n 'deny': deny_rule,\n 'eml': eml_rule,\n 'givenName': any_name_rule,\n 'individualName': individual_name_rule,\n 'metadata': metadata_rule,\n 'organizationName': any_name_rule,\n 'permission': permission_rule,\n 'positionName': any_name_rule,\n 'principal': principal_rule,\n 'salutation': any_name_rule,\n 'surName': any_name_rule,\n 'title': title_rule,\n 'value': value_rule,\n}\n\n\ndef main():\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/eml2_1_1/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"472094544","text":"import gzip\nimport numpy as np\nfrom collections import namedtuple\n\nfrom .subblocks import (\n parse_run_header,\n parse_event_header,\n parse_event_end,\n parse_cherenkov_photons,\n parse_particle_data,\n parse_longitudinal,\n parse_run_end,\n get_version,\n)\nfrom .subblocks.longitudinal import longitudinal_header_dtype\nfrom .subblocks.data import mmcs_cherenkov_photons_dtype\nfrom .io import read_block, read_buffer_size\n\nfrom .constants import BLOCK_SIZE_BYTES, EVTH_VERSION_POSITION\n\nEvent = namedtuple('Event', ['header', 'data', 'longitudinal', 'end'])\nPhotonEvent = namedtuple('PhotonEvent', ['header', 'photons', 'longitudinal', 'end'])\nParticleEvent = namedtuple('ParticleEvent', ['header', 'particles', 'longitudinal', 'end'])\n\n\ndef is_gzip(f):\n pos = f.tell()\n f.seek(0)\n b1, b2 = f.read(2)\n f.seek(pos)\n\n return (b1 == 0x1f) and (b2 == 0x8b)\n\n\nclass CorsikaFile:\n\n def __init__(self, path):\n self.EventClass = Event\n\n self._f = open(path, 'rb')\n if is_gzip(self._f):\n self._f = gzip.open(path)\n\n self._buffer_size = read_buffer_size(self._f)\n\n runh_bytes = self.read_block()\n if not runh_bytes[:4] == b'RUNH':\n raise ValueError('File does not start with b\"RUNH\"')\n\n self.run_header = parse_run_header(runh_bytes)[0]\n self.version = round(float(self.run_header['version']), 4)\n self._run_end = None\n\n @property\n def run_end(self):\n if self._run_end is None:\n pos = self._f.tell()\n\n if self._buffer_size is None:\n self._f.seek(0, 2)\n else:\n self._f.seek(-4, 2)\n\n self._f.seek(-BLOCK_SIZE_BYTES, 1)\n block = self.read_block()\n while block[:4] != b'RUNE':\n self._f.seek(-2 * BLOCK_SIZE_BYTES, 1)\n block = self.read_block()\n\n self._run_end = parse_run_end(block)[0]\n self._f.seek(pos)\n\n return self._run_end\n\n def __next__(self):\n block = self.read_block()\n\n if block[:4] == b'RUNE':\n self._run_end = parse_run_end(block)\n raise StopIteration()\n\n if len(block) < BLOCK_SIZE_BYTES:\n raise StopIteration\n\n if block[:4] != b'EVTH':\n raise IOError('EVTH block expected but found {}'.format(block[:4]))\n\n event_header = parse_event_header(block)[0]\n\n block = self.read_block()\n data_bytes = bytearray()\n long_bytes = bytearray()\n\n while block[:4] != b'EVTE':\n\n if block[:4] == b'LONG':\n long_bytes += block[longitudinal_header_dtype.itemsize:]\n else:\n data_bytes += block\n\n block = self.read_block()\n\n event_end = parse_event_end(block)[0]\n data = self.parse_data_blocks(data_bytes)\n longitudinal = parse_longitudinal(long_bytes)\n\n return self.EventClass(event_header, data, longitudinal, event_end)\n\n @classmethod\n def parse_data_blocks(cls, data_bytes):\n array = np.frombuffer(data_bytes, dtype='float32').reshape(-1, 7)\n return array[np.any(array != 0, axis=1)]\n\n def __iter__(self):\n return self\n\n def read_headers(self):\n pos = self._f.tell()\n self._f.seek(0)\n\n block = self.read_block()\n event_header_data = bytearray()\n end_found = True\n\n while block:\n if block[:4] == b'RUNE':\n self._run_end = parse_run_end(block)[0]\n break\n\n if block[:4] == b'EVTH' and get_version(block, EVTH_VERSION_POSITION) == self.version:\n if not end_found:\n raise IOError('Expected EVTE block before next EVTH')\n\n event_header_data += block\n\n end_found = False\n elif block[:4] == b'EVTE':\n end_found = True\n\n block = self.read_block()\n\n self._f.seek(pos)\n\n event_headers = parse_event_header(event_header_data)\n\n return self.run_header, event_headers, self._run_end\n\n def read_block(self):\n return read_block(self._f, self._buffer_size)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n def close(self):\n self._f.close()\n\n\nclass CorsikaCherenkovFile(CorsikaFile):\n\n def __init__(self, path, mmcs=False):\n super().__init__(path)\n\n self.EventClass = PhotonEvent\n self.mmcs = mmcs\n\n def parse_data_blocks(self, data_bytes):\n photons = parse_cherenkov_photons(data_bytes)\n if not self.mmcs:\n return photons\n\n mmcs = np.empty(len(photons), dtype=mmcs_cherenkov_photons_dtype)\n\n for col in ('x', 'y', 'u', 'v', 't', 'production_height'):\n mmcs[col] = photons[col]\n\n mmcs['n_photons'] = 1.0\n mmcs['wavelength'] = photons['n_photons'] % 1000\n mmcs['mother_particle'] = photons['n_photons'] // 100000\n\n return mmcs\n\n\nclass CorsikaParticleFile(CorsikaFile):\n\n def __init__(self, path):\n super().__init__(path)\n self.EventClass = ParticleEvent\n\n def parse_data_blocks(self, data_bytes):\n return parse_particle_data(data_bytes)\n","sub_path":"corsikaio/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"298279645","text":"class XLSUploadAPI(APIView):\r\n def post(self,request):\r\n form=XLSUploadForm(request.POST,request.FILES)\r\n if form.is_valid():\r\n file=form.cleaned_data[\"xlsfile\"]\r\n sysname=form.cleaned_data[\"sysname\"]\r\n chartname=form.cleaned_data[\"chartname\"]\r\n if Chart.objects.filter(chartname=chartname,system_sysname=sysname).exists():\r\n return self.error('Chart already exists')\r\n system=System.objects.get(sysname=sysname)\r\n chart=Chart.objects.create(system=system,chartname=chartname)\r\n db=oracle.connect('usr_exgdba/4f583b94@172.16.11.16/ywxtdb')\r\n cursor=db.cursor()\r\n xlsfile=xlrd.open_workbook(filename=None,file_contents=file)\r\n sheet=xlsfile.sheet_by_index(0)\r\n realnames=sheet.row_values(0)\r\n colnames=[]\r\n for i in realnames:\r\n name=''.join(lazy_pinyin(i))\r\n if name in colnames:\r\n j=0\r\n while name in colnames:\r\n name=name+str(j)\r\n j=j+1\r\n colnames.append(name)\r\n col=Column.objects.create(chart=chart,realname=i,colname=name)\r\n\r\n sql=\"create table %s(id number(10) primary key\" % chartname\r\n for i in colnames:\r\n sql=sql+\",%s varchar2(200)\" % i\r\n sql=sql+')'\r\n result=cursor.excute(sql)\r\n return self.success()","sub_path":"backupfororacle.py","file_name":"backupfororacle.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"287919119","text":"def shipping_ground(weight):\n if weight <= 2:\n price_pound = 1.50\n elif weight <= 6:\n price_pound = 3.00\n elif weight <= 10:\n price_pound = 4.00\n else:\n price_pound = 4.75\n return (weight * price_pound) + 20.00\nprint(shipping_ground(8.4))\n\nshipping_ground_premium = 125.00\n\ndef shipping_dron(weight):\n if weight <= 2:\n price_pound = 4.50\n elif weight <= 6:\n price_pound = 9.00\n elif weight <= 10:\n price_pound = 12.00\n else:\n price_pound = 14.25\n return (weight * price_pound)\nprint(shipping_dron(1.5))\n \n \ndef shipping_cheapest(weight):\n ground = shipping_ground(weight)\n dron = shipping_dron(weight)\n premium = shipping_ground_premium(weight)\n if ground < dron and ground < premium:\n return ground\n elif dron < ground and dron < premium:\n return shipping_dron\n else:\n return premium\n \n cheapest = shipping_cheapest(4.8)\n print(\"cheapest: \", cheapest)\n \n \n ","sub_path":"section-python/section-function-lists/function-shipping.py","file_name":"function-shipping.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"56095855","text":"import numpy as np\r\nfrom scipy.sparse import rand\r\nfrom skfeature.function.structure import group_fs\r\n\r\n\r\ndef main():\r\n n_samples = 50 # specify the number of samples in the simulated data\r\n n_features = 100 # specify the number of features in the simulated data\r\n\r\n # simulate the dataset\r\n X = np.random.rand(n_samples, n_features)\r\n\r\n # simulate the feature weight\r\n w_orin = rand(n_features, 1, 1).toarray()\r\n w_orin[0:50] = 0\r\n\r\n # obtain the ground truth of the simulated dataset\r\n noise = np.random.rand(n_samples, 1)\r\n y = np.dot(X, w_orin) + 0.01 * noise\r\n y = y[:, 0]\r\n\r\n z1 = 0.1 # specify the regularization parameter of L1 norm\r\n z2 = 0.1 # specify the regularization parameter of L2 norm for the non-overlapping group\r\n\r\n # specify the group structure among features\r\n idx = np.array([[1, 20, np.sqrt(20)], [21, 40, np.sqrt(20)], [41, 50, np.sqrt(10)],\r\n [51, 70, np.sqrt(20)], [71, 100, np.sqrt(30)]]).T\r\n idx = idx.astype(int)\r\n\r\n # perform feature selection and obtain the feature weight of all the features\r\n w, obj, value_gamma = group_fs.group_fs(X, y, z1, z2, idx, verbose=True)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Pattern-Recognition/hw2-Feature-Selection/skfeature/example/test_group_fs.py","file_name":"test_group_fs.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307907497","text":"from django import forms\nfrom django_summernote.widgets import SummernoteWidget\nfrom board.models import Post, Comment\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('title','content')\n #exclude = ('created_at','updated_at')\n widgets = {\n 'title': forms.TextInput(attrs={'placeholder': '제목'}),\n 'content': SummernoteWidget(),\n }\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('content',)\n\n","sub_path":"udecide/board/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"576130807","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 17:07:43 2019\n\n@author: Bill\n\"\"\"\n\nimport asyncio\nimport time\n\nclass status():\n def __init__(self):\n self.done = False\n\ndef fire_and_forget(f):\n def wrapped(*args, **kwargs):\n return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)\n\n return wrapped\n#\n# I do not understand why, but I can only get this to work using a decorator. I kind of\n# find decorators annoying. But I can't get the arguments to work correctly otherwise. \n# At this point I guess I can just decorate the call to trainer, like below, and then \n# I should be able to send commands to it from the Matplotlib interface. \n# \n# Here what happens is \n#\n@fire_and_forget\ndef foo(st):\n print('done is',st.done)\n while not st.done:\n time.sleep(1.0)\n print('looping...done is',st.done)\n print(\"foo() completed\")\n return\n\n\nstat = status()\nprint(\"Hello\")\n#fire_and_forget(foo,stat)\nfoo(stat)\n#foo = fire_and_forget(foo)\n\nprint(\"I didn't wait for foo()\")\n","sub_path":"fire_and_forget.py","file_name":"fire_and_forget.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"214860288","text":"from pytube import YouTube\r\nimport sys\r\n\r\nlink_file = open('/nfs/home/ryan0507/ybigta/link_list2.txt')\r\nline = link_file.readline().rstrip('\\n')\r\ncnt = 21\r\nlabel_file = open('/nfs/home/ryan0507/ybigta/original_files.txt', mode = \"w\")\r\nwhile line:\r\n yt = YouTube(line)\r\n yt = yt.streams.first()\r\n print('Downloading ' + line)\r\n yt.download(output_path='/nfs/home/ryan0507/bmt/sample/', filename='test_'+str(cnt))\r\n print(line , 'downloaded with test_' + str(cnt))\r\n label_file.write('test_' + str(cnt) + ' : ' + line + '\\n')\r\n cnt += 1\r\n line = link_file.readline().rstrip('\\n')\r\n\r\n\r\n","sub_path":"model/video-captioning/bmt/pytube_link2.py","file_name":"pytube_link2.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"46372316","text":"\nimport sys\nsys.path.append(\"../../../pygra\") # add pygra library\n\n# Compute the Gap of a honeycomb lattice as a function of the sublattice\n# imbalance\n\nimport geometry\nimport gap\nimport numpy as np\n\nms = np.linspace(0.,0.3,30)\ngs = [] # storage for the gaps\nfor m in ms:\n g = geometry.honeycomb_lattice()\n h = g.get_hamiltonian(has_spin=True)\n h.add_sublattice_imbalance(m)\n gg = gap.indirect_gap(h)\n gs.append(gg) # append gap\n print(m,gg,gg/m)\n\n\n\nimport matplotlib.pyplot as plt\nplt.plot(ms,gs)\nplt.xlabel(\"mass\")\nplt.ylabel(\"gap\")\nplt.show()\n\n","sub_path":"examples/2d/gap/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"296459918","text":"from oslo_config import cfg\nimport oslo_messaging as msg\n\n\nclass client(object):\n def __init__(self, transport, target):\n self.transport = transport\n self.target = target\n self._client = msg.RPCClient(self.transport, self.target)\n\n def test(self):\n self._client.call(ctxt={}, method = 'test', arg=\"Hey. This is testing my coding skills\")\n\n# Create Messaging Transport\ntransport = msg.get_transport(cfg.CONF)\n# Create Target\ntarget = msg.Target(topic='trungnv')\n\n# Create RPC client\nrpc_client = client(transport,target)\n\n# Call function\nrpc_client.test()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"26094350","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/c24b/projets/crawtext/newspaper/videos/extractors.py\n# Compiled at: 2014-11-06 08:50:32\nfrom .videos import Video\nVIDEOS_TAGS = [\n 'iframe', 'embed', 'object', 'video']\nVIDEO_PROVIDERS = ['youtube', 'vimeo', 'dailymotion', 'kewego']\n\nclass VideoExtractor(object):\n \"\"\"Extracts a list of video from Article top node\n \"\"\"\n\n def __init__(self, config, top_node):\n self.config = config\n self.parser = self.config.get_parser()\n self.top_node = top_node\n self.candidates = []\n self.movies = []\n\n def get_embed_code(self, node):\n return ('').join([ line.strip() for line in self.parser.nodeToString(node).splitlines()\n ])\n\n def get_embed_type(self, node):\n return self.parser.getTag(node)\n\n def get_width(self, node):\n return self.parser.getAttribute(node, 'width')\n\n def get_height(self, node):\n return self.parser.getAttribute(node, 'height')\n\n def get_src(self, node):\n return self.parser.getAttribute(node, 'src')\n\n def get_provider(self, src):\n if src:\n for provider in VIDEO_PROVIDERS:\n if provider in src:\n return provider\n\n return\n\n def get_video(self, node):\n \"\"\"Create a video object from a video embed\n \"\"\"\n video = Video()\n video.embed_code = self.get_embed_code(node)\n video.embed_type = self.get_embed_type(node)\n video.width = self.get_width(node)\n video.height = self.get_height(node)\n video.src = self.get_src(node)\n video.provider = self.get_provider(video.src)\n return video\n\n def get_iframe_tag(self, node):\n return self.get_video(node)\n\n def get_video_tag(self, node):\n \"\"\"Extract html video tags\n \"\"\"\n return Video()\n\n def get_embed_tag(self, node):\n parent = self.parser.getParent(node)\n if parent is not None:\n parent_tag = self.parser.getTag(parent)\n if parent_tag == 'object':\n return self.get_object_tag(node)\n return self.get_video(node)\n\n def get_object_tag(self, node):\n child_embed_tag = self.parser.getElementsByTag(node, 'embed')\n if child_embed_tag and child_embed_tag[0] in self.candidates:\n self.candidates.remove(child_embed_tag[0])\n src_node = self.parser.getElementsByTag(node, tag='param', attr='name', value='movie')\n if not src_node:\n return None\n else:\n src = self.parser.getAttribute(src_node[0], 'value')\n provider = self.get_provider(src)\n if not provider:\n return None\n video = self.get_video(node)\n video.provider = provider\n video.src = src\n return video\n\n def get_videos(self):\n self.candidates = self.parser.getElementsByTags(self.top_node, VIDEOS_TAGS)\n for candidate in self.candidates:\n tag = self.parser.getTag(candidate)\n attr = 'get_%s_tag' % tag\n if hasattr(self, attr):\n movie = getattr(self, attr)(candidate)\n if movie is not None and movie.provider is not None:\n self.movies.append(movie)\n\n return list(self.movies)","sub_path":"pycfiles/crawtext-4.1.1-py2-none-any/extractors.py","file_name":"extractors.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290075782","text":"import threading\nfrom tkinter import *\nimport json\nimport tkinter.scrolledtext as tkscrolled\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nfrom matplotlib.figure import Figure\n\nwith open(\"configuration.json\", 'r+') as configuration_file:\n elasticsearch_directory = json.load(configuration_file)[\"elasticsearch_directory\"]\n configuration_file.close()\n\nimport sys\n\nsys.path.append(elasticsearch_directory)\n\ntry:\n from search_api import *\nexcept:\n print(\"No Elasticsearch module found\")\n exit(1)\n\n\nclass App(Frame):\n \"\"\"\n This class contains the main functionality of the Kibana GUI.\n \"\"\"\n\n class Constants():\n \"\"\"\n This class contains the constants used in the GUI creation\n \"\"\"\n START_OF_FILE = 1.0\n TOP_FRAME_HEIGHT = 50\n\n def __init__(self, master):\n \"\"\"\n This parameter initializes the main App frame (and configures it) and calls the method to create\n all of the app widgets.\n :param master: Main Window\n \"\"\"\n super().__init__()\n self.master = master\n self.figure = Figure()\n\n self.default_query = \"16042018 http clientIP all size_response all ORDER clientIP\"\n #self.default_query = \"16042018 http clientIP all GROUP\"\n #self.default_query = \"16042018 http clientIP 131.174.154.24 size_response all COUNT\"\n self.last_query = \"\"\n\n self.search_engine = Elasticsearch()\n\n self.has_been_just_launched = True\n self.createWidgets(self.master)\n\n def update_text_ui(self, original_logs, bottom):\n \"\"\"\n This method updates the ScrollableText Widget that displays the logs that are a match with the query.\n\n :param original_logs: logs that are a match with the query\n :param bottom: ScrollableText widget that contains the logs\n :return: The function does not return anything.\n \"\"\"\n\n new_text = \"\\n\\n\"\n log_counter = 0\n for log in original_logs:\n new_text += \"Log number \" + str(log_counter) + \": \\n\\n\"\n log_counter += 1\n\n for key in log.keys():\n if str(log[key]) != \"-\":\n new_text = new_text + key + \": \" + str(log[key]) + \"\\n\"\n\n new_text += \"\\n\\n\"\n\n bottom.config(state=NORMAL)\n bottom.delete(self.Constants.START_OF_FILE, END)\n bottom.insert(self.Constants.START_OF_FILE, new_text)\n bottom.config(state=DISABLED)\n\n def update_graphic_ui(self, query, top, results):\n \"\"\"\n This method updates the Frame Widget that displays the graphic result.\n\n :param query: query performed\n :param top: frame that contains the graphic/s\n :param results: result of the query\n :return: The method does not return anything\n \"\"\"\n\n split_query = query.split(\" \")\n _, _, _, pairs, action = self.search_engine.getQueryInfo(elasticsearch_directory, split_query)\n\n if action == \"COUNT\":\n # Create graphic based on the result of the COUNT action result structure\n x_axis_title = \"\"\n for pair in pairs:\n x_axis_title += pair[0] + \": \" + pair[1] + \" \"\n\n y_pos = np.arange(1)\n\n plt.rcdefaults()\n fig, ax = plt.subplots(figsize=(5, 1))\n\n ax.barh(results, results, align='center')\n ax.set_yticks(y_pos)\n ax.set_xlabel(\"Count - \" + x_axis_title)\n ax.set_title('Query Results')\n\n fig.tight_layout()\n\n # Now we integrate the graphic with the Graphic UI\n self.figure = fig\n top.figure = self.figure\n top.draw()\n top.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)\n\n elif action == \"GROUP\":\n # Create graphic based on the result of the GROUP action result structure\n y_axis_name = \"Count\"\n\n results.keys()\n\n fig = plt.figure(figsize=(12, 3))\n s = fig.add_subplot(111)\n\n y_pos = np.arange(len(results.keys()))\n y_axis_values = []\n\n objects = []\n\n for key in results.keys():\n y_axis_values.append(results[key])\n objects.append(key)\n\n s.bar(y_pos, y_axis_values, align='center')\n plt.xticks(y_pos, objects)\n s.set_xticklabels(objects)\n s.set_ylabel(y_axis_name)\n s.set_title('Query Results')\n\n for ax in fig.axes:\n matplotlib.pyplot.sca(ax)\n plt.xticks(rotation=45)\n\n fig.tight_layout()\n\n # Now we integrate the graphic with the Graphic UI\n self.figure = fig\n top.figure = self.figure\n top.draw()\n top.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)\n\n elif action == \"ORDER\":\n # Create graphic based on the result of the ORDER action result structure\n\n # Check that the there are 2 field-value pairs in the query, just in case\n if len(pairs) == 2:\n fig, ax1 = plt.subplots(figsize=(12, 5))\n\n y_axis_name = \"Count\"\n objects = results.keys()\n y_pos = np.arange(len(objects))\n y_axis_values = []\n\n data = []\n for key in results.keys():\n y_axis_values.append(results[key][\"count\"])\n data.append(results[key][pairs[-1][0]])\n\n plt.bar(y_pos, y_axis_values, align='center')\n plt.xticks(y_pos, objects)\n plt.xticks(rotation=-90)\n plt.ylabel(y_axis_name)\n plt.title('Query Results')\n\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\n color = 'tab:red'\n ax2.set_ylabel([pairs[-1][0]], color=color) # we already handled the x-label with ax1\n ax2.plot(objects, data, color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n\n fig.tight_layout() # otherwise the right y-label is slightly clipped\n\n # Now we integrate the graphic with the Graphic UI\n self.figure = fig\n top.figure = self.figure\n top.draw()\n top.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)\n else:\n pass\n\n def update_ui(self, top, bottom, original_logs, results, elasticsearch_directory, query):\n \"\"\"\n This method updates the UI with the result of the query --graphic and text---.\n\n :param top: Frame that contains the graphic\n :param bottom: ScrollableText widget that contains the logs\n :param original_logs: logs that are a match with the query\n :param results: result of the query, that is the action performed over the logs that are a match with the\n query.\n :param elasticsearch_directory:\n :return: This function does not return anything.\n \"\"\"\n\n print(\"Updating UI in update_ui method\")\n\n # Update Text UI in thread, so UI doesn't freeze\n new_text_thread = threading.Thread(\n target=self.update_text_ui(original_logs, bottom))\n new_text_thread.run()\n\n # Update Graphic UI in thread, so UI doesn't freeze\n new_graphic_thread = threading.Thread(\n target=self.update_graphic_ui(query, top,results))\n new_graphic_thread.run()\n\n print(\"Leaving update_ui method\")\n\n def search(self, top, bottom, search, query=None):\n \"\"\"\n This method is the bridge between the UI, the Elasticsearch API and the UI Updater\n\n :param top: Frame widget that contains the graphic\n :param bottom: ScrollableText widget that contains the logs that are a match with the query.\n :param search: SearchBar widget\n :param query: query that will be performed in the Elasticsearch API\n :return: this function does not return anything\n \"\"\"\n\n print(\"Entering search method in Kibana GUI\\n\")\n\n with open(\"configuration.json\", 'r+') as configuration_file:\n elasticsearch_directory = json.load(configuration_file)[\"elasticsearch_directory\"]\n configuration_file.close()\n\n if query is not None:\n original_logs, results = self.search_engine.search(elasticsearch_directory, query)\n else:\n original_logs, results = self.search_engine.search(elasticsearch_directory, search.get())\n query = search.get()\n\n new_thread = threading.Thread(\n target=self.update_ui(top, bottom, original_logs, results, elasticsearch_directory, query))\n new_thread.run()\n\n print(\"Leaving search method in Kibana GUI\")\n\n def createWidgets(self, master):\n \"\"\"\n This method creates all of the Tkinter widgets that are part of the UI\n :param master: Main Window of the App, that will contain all the widgets created\n :return: The method does not return anything\n \"\"\"\n\n with open(\"configuration.json\", 'r+') as configuration_file:\n elasticsearch_directory = json.load(configuration_file)[\"elasticsearch_directory\"]\n configuration_file.close()\n\n # Create all of the main containers\n dark_grey = '#898686'\n light_grey = '#c1c1c1'\n\n top_frame = Frame(master, bg=dark_grey, width=master.winfo_width(), height=self.Constants.TOP_FRAME_HEIGHT)\n center_bottom_frame = Frame(master, bg=light_grey, width=master.winfo_width())\n\n # layout all of the main containers\n master.grid_rowconfigure(1, weight=1)\n master.grid_columnconfigure(0, weight=1)\n\n top_frame.grid(row=0, sticky=\"ew\")\n center_bottom_frame.grid(row=1, sticky=\"nsew\")\n\n # create the center widgets\n center_bottom_frame.grid_rowconfigure(0, weight=1)\n center_bottom_frame.grid_columnconfigure(1, weight=1)\n\n ctr_bottom_left = Frame(center_bottom_frame, bg=dark_grey, width=254)\n ctr_bottom_mid_right = Frame(center_bottom_frame)\n ctr_bottom_mid_right_top = FigureCanvasTkAgg(self.figure, master=ctr_bottom_mid_right)\n ctr_bottom_mid_right_bottom = Frame(ctr_bottom_mid_right, bg=\"white\")\n\n ctr_bottom_left.grid(row=0, column=0, sticky=\"ns\")\n ctr_bottom_mid_right_top.draw()\n ctr_bottom_mid_right_top.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True)\n ctr_bottom_mid_right.grid(row=0, column=1, sticky=\"nsew\")\n ctr_bottom_mid_right_bottom.pack(fill=BOTH)\n\n # Create and configure the query result label (title)\n query_result_title = Label(ctr_bottom_mid_right_bottom)\n query_result_title.config(text=\"Logs that are a match with the query\", font='Helvetica 14 bold',\n bg=\"white\", width=164, anchor=W, justify=LEFT)\n query_result_title.grid(row=0, column=0)\n\n text_wrapper = Frame(ctr_bottom_mid_right_bottom)\n text_wrapper.config(height=500)\n text_wrapper.grid(row=1, column=0, sticky=\"nswe\")\n\n bottom_text = tkscrolled.ScrolledText(text_wrapper, bg=\"white\")\n bottom_text.grid(row=0)\n bottom_text['font'] = ('Helvetica', '12')\n\n # Create left panel label (title)\n left_label_title = Label(ctr_bottom_left)\n left_label_title.config(text=\"Available Indexes\", bg=\"white\", font='Helvetica 14 bold', width=32,\n justify=LEFT)\n left_label_title.place(x=ctr_bottom_left.winfo_x(), y=ctr_bottom_left.winfo_y())\n\n # Create left panel list (body) and scrollbar\n available_indexes = self.search_engine.available_indexes(elasticsearch_directory)\n\n listbox = Listbox(ctr_bottom_left, bg=\"white\", width=int(master.winfo_width()*0.025), height=500,\n selectmode=MULTIPLE)\n listbox.place(x=left_label_title.winfo_x(), y=left_label_title.winfo_y() + 22)\n\n for i in range(0, len(available_indexes)):\n listbox.insert(i + 1, available_indexes[i])\n\n # Create and configure the search bar\n search_bar = Entry(top_frame, bg=\"white\", text=\"Search Here\", width=int(master.winfo_width()*0.1118))\n search_bar.grid(row=0, column=0)\n search_button = Button(top_frame, bg='white', text=\"Search\", width=int(master.winfo_width()*0.01),\n command=lambda top=ctr_bottom_mid_right_top, bottom=bottom_text,\n search=search_bar:\n self.search(top, bottom, search))\n search_button.grid(row=0, column=1)\n\n # When the UI is launched for the first time, we show a default query so that the UI is not empty.\n if self.has_been_just_launched:\n self.search(ctr_bottom_mid_right_top, bottom_text, search_bar, query=self.default_query)\n self.has_been_just_launched = False\n\n\nif __name__ == \"__main__\":\n root = Tk()\n root.title(\"Log Management System v1\")\n canvas = Canvas(root, width=2000, height=1000)\n canvas.pack()\n canvas.update()\n my_gui = App(canvas)\n my_gui.mainloop()","sub_path":"Log Manager in Python/kibana/kibana_ui.py","file_name":"kibana_ui.py","file_ext":"py","file_size_in_byte":13365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502501537","text":"\nimport requests\nimport re\nimport json\nimport time\nimport random\n\nMAXSLEEPTIME = 3\nMINSLEEPTIME = 1\nSTATUS_OK = 200\nMAX_PAGE_NUM = 10\nSERVER_ERROR_MIN = 500\nSERVER_ERROR_MAX = 600\nCLIENT_ERROR_MIN = 400\nCLIENT_ERROR_MAX = 500\n\n#1.对URL发起HTTP请求http request,得到相应的http response响应,response响应体中有我们需要的数据内容。\ndef get_one_page(URL,num_retry=5): #https://maoyan.com/board/4?offset=0\n if num_retry == 0:\n return None\n ua_headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36\"}\n response = requests.get(URL,headers=ua_headers)\n if response.status_code == STATUS_OK:\n return response.text\n elif SERVER_ERROR_MIN <= response.status_code < SERVER_ERROR_MAX:\n time.sleep(MAXSLEEPTIME)\n get_one_page(URL,num_retry-1)\n elif CLIENT_ERROR_MIN <= response.status_code < CLIENT_ERROR_MAX:\n #正确的做法是写日志\n if response.status_code == 404:\n print(\"Page not find!\") \n elif response.status_code == 403:\n print(\"Forbidden!\")\n else:\n pass\n return None\n\n#print(get_one_page(\"https://maoyan.com/board/4?offset=0\"))\n\n#2.使用正则表达式,XPath,bs4精确的获取数据。\ndef parse_one_page(html):\n pattern = re.compile('

.*?title=\"([\\s\\S]*?)\"[\\s\\S]*?

([\\s\\S]*?)

[\\s\\S]*?

([\\s\\S]*?)

')\n items = re.findall(pattern,html)\n for i in items:\n yield{\n \"title\":i[0].strip(),\n \"actor\":i[1].strip(),\n \"time\":i[2].strip()\n }\n \n#parse_one_page(get_one_page(\"https://maoyan.com/board/4?offset=0\"))\n\n#3.将数据存到本地的文件系统中或者数据库中。\ndef write_to_file(item):\n with open(\"猫眼.txt\",'a',encoding=\"utf-8\") as f:\n f.write(json.dumps(item,ensure_ascii=False)+'\\n')\n \n#4.控制整个爬取一个网页的流程。\ndef crawl_one_page(offset):\n #拼出一个url\n url = \"https://maoyan.com/board/4?offset=\"+str(offset)\n #下载这个url\n html = get_one_page(url)\n #解析每个页面,并且把获取到的item一个一个写入文件\n for item in parse_one_page(html):\n write_to_file(item)\n time.sleep(random.randint(MINSLEEPTIME,MAXSLEEPTIME)) #随机休息1-5秒之后再进行下一次爬取。\n\nif __name__ == \"__main__\":\n for i in range(MAX_PAGE_NUM):\n crawl_one_page(i*MAX_PAGE_NUM)\n\n\n","sub_path":"aid1805/pbase/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"315407032","text":"# Given a string of words, you need to find the highest scoring word.\n# Each letter of a word scores points according to its position in the \n# alphabet: a = 1, b = 2, c = 3 etc.\n# You need to return the highest scoring word as a string.\n# If two words score the same, return the word that appears earliest in the \n# original string.\n# All letters will be lowercase and all inputs will be valid.\n\ndef high(x):\n s_word = ''\n s_score = 0\n for word in x.split(' '):\n score = 0\n for c in word:\n score += (ord(c) - 96) # ACII order\n if score > s_score:\n s_score = score\n s_word = word\n return s_word","sub_path":"CodeWars/6kyu/highest_scoring_word.py","file_name":"highest_scoring_word.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"522614306","text":"import os\n\nfrom requests.exceptions import RequestException\nimport pytest\nfrom unittest.mock import create_autospec, Mock\n\nfrom pyquil.api import WavefunctionSimulator, ForestConnection, QVMConnection, get_benchmarker\nfrom pyquil.api._errors import UnknownApiError\nfrom pyquil.paulis import sX\nfrom pyquil import Program, get_qc\nfrom pyquil.gates import I, MEASURE\nfrom pyquil.device import ISA, Device\n\n\n\nPATH = os.path.dirname(os.path.realpath(__file__))\nRACK_YAML = os.path.join(PATH, \"example_rack.yaml\")\n\n\n@pytest.fixture(scope='module')\ndef qvm():\n try:\n qc = get_qc('9q-square-qvm')\n qc.compiler.client.timeout = 1\n qc.run_and_measure(Program(I(0)), trials=1)\n return qc\n except (RequestException, TimeoutError) as e:\n return pytest.skip(\"This test requires a running local QVM and quilc: {}\".format(e))\n\n\n@pytest.fixture(scope='session')\ndef forest():\n try:\n connection = ForestConnection()\n connection._wavefunction(Program(I(0)), 52)\n return connection\n except (RequestException, UnknownApiError) as e:\n return pytest.skip(\"This test requires a Forest connection: {}\".format(e))\n\n\n@pytest.fixture(scope='session')\ndef wfn(forest):\n return WavefunctionSimulator(connection=forest)\n\n\n@pytest.fixture(scope='session')\ndef cxn():\n # DEPRECATED\n try:\n cxn = QVMConnection(endpoint='http://localhost:5000')\n cxn.run(Program(I(0), MEASURE(0, 0)), [0])\n return cxn\n except RequestException as e:\n return pytest.skip(\"This test requires a running local QVM: {}\".format(e))\n\n\n@pytest.fixture(scope='session')\ndef benchmarker():\n try:\n benchmarker = get_benchmarker(timeout=1)\n benchmarker.apply_clifford_to_pauli(Program(I(0)), sX(0))\n return benchmarker\n except (RequestException, TimeoutError) as e:\n return pytest.skip(\"This test requires a running local benchmarker endpoint (ie quilc): {}\"\n .format(e))\n\n\n@pytest.fixture(scope='session')\ndef mock_get_devices():\n # Generated from ISA.to_dict.\n acorn = {'1Q': {'0': {}, '1': {}, '2': {}, '3': {'dead': True}, '4': {}, '5': {}, '6': {}, '7': {}, '8': {},\n '9': {}, '10': {}, '11': {}, '12': {}, '13': {}, '14': {}, '15': {}, '16': {}, '17': {}, '18': {},\n '19': {}},\n '2Q': {'0-5': {}, '0-6': {}, '1-6': {}, '1-7': {}, '2-7': {}, '2-8': {}, '4-9': {}, '5-10': {}, '6-11': {},\n '7-12': {}, '8-13': {}, '9-14': {}, '10-15': {}, '10-16': {}, '11-16': {}, '11-17': {}, '12-17': {},\n '12-18': {}, '13-18': {}, '13-19': {}, '14-19': {}}}\n agave = {'1Q': {'0': {}, '1': {}, '2': {}, '3': {}, '4': {}, '5': {}, '6': {}, '7': {}},\n '2Q': {'0-1': {}, '1-2': {}, '2-3': {}, '3-4': {}, '4-5': {}, '5-6': {}, '6-7': {}, '7-0': {}}}\n mock_acorn = Mock(spec=Device)\n mock_agave = Mock(spec=Device)\n mock_acorn.isa = ISA.from_dict(acorn)\n mock_agave.isa = ISA.from_dict(agave)\n\n # Make sure we are matching the signature.\n mocked_function = create_autospec(get_devices)\n\n def side_effect(as_dict=True):\n if as_dict:\n return {'19Q-Acorn': mock_acorn,\n '8Q-Agave': mock_agave}\n else:\n return {acorn, agave}\n mocked_function.side_effect = side_effect\n return mocked_function\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--runslow\", action=\"store_true\", default=False, help=\"run slow tests\"\n )\n\n\ndef pytest_collection_modifyitems(config, items):\n if config.getoption(\"--runslow\"):\n # --runslow given in cli: do not skip slow tests\n return\n skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n for item in items:\n if \"slow\" in item.keywords:\n item.add_marker(skip_slow)","sub_path":"forest/benchmarking/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"297702866","text":"# Copyright 2017 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n\nfrom hashlib import sha512\nfrom random import randint\nfrom google.protobuf.message import DecodeError\n\nfrom sawtooth_signing.secp256k1_signer import sign\nfrom sawtooth_signing.secp256k1_signer import generate_public_key\nfrom sawtooth_sdk.protobuf.batch_pb2 import Batch\nfrom sawtooth_sdk.protobuf.batch_pb2 import BatchHeader\nfrom sawtooth_sdk.protobuf.batch_pb2 import BatchList\nfrom sawtooth_sdk.protobuf.transaction_pb2 import Transaction\nfrom sawtooth_sdk.protobuf.transaction_pb2 import TransactionHeader\nfrom sawtooth_sdk.protobuf.transaction_pb2 import TransactionList\n\n\ndef _listify(item_or_items):\n \"\"\"Wraps an item in a list if it is not already a list\n \"\"\"\n if isinstance(item_or_items, list):\n return item_or_items\n return [item_or_items]\n\n\nclass TransactionEncoder(object):\n \"\"\"Stores a private key and default TransactionHeader values, which will\n then be used to create and serialize Transactions. Any TransactionHeader\n value set will be used with EVERY Transaction this encoder creates.\n\n Args:\n private_key (bytes): The private key to sign Transactions with\n payload_encoder (function, optional): Run on each payload before\n creating Transaction, must return bytes\n batcher_public_key (string or bytes, optional): Expected batcher public\n key\n dependencies (list of str, optional): Transaction ids that must be\n committed before every Transaction from this encoder (unusual)\n family_name (str, optional): Name of the designated Transaction Family\n family_version (str, optional): Version of Transaction Family\n inputs (list of str, optional): State addresses that every Transaction\n created by this encoder will read from (unusual)\n outputs (list of str, optional): State addresses that every Transaction\n created by this encoder will write to (unusual)\n\n Note:\n Every optional argument can be set or changed later as an attribute.\n \"\"\"\n def __init__(self,\n private_key,\n payload_encoder=lambda x: x,\n batcher_public_key=None,\n dependencies=None,\n family_name=None,\n family_version=None,\n inputs=None,\n outputs=None):\n self._private_key = private_key\n self._public_key = generate_public_key(\n private_key, private_key_format='bytes')\n\n self.payload_encoder = payload_encoder\n\n # Set default headers as attributes so they can be modified later\n self.batcher_public_key = (self._public_key\n if batcher_public_key is None\n else batcher_public_key)\n self.dependencies = dependencies\n self.family_name = family_name\n self.family_version = family_version\n self.inputs = inputs\n self.outputs = outputs\n\n def create(self,\n payload,\n batcher_public_key=None,\n dependencies=None,\n family_name=None,\n family_version=None,\n inputs=None,\n nonce=None,\n outputs=None):\n \"\"\"Creates a new Transaction from a payload, and a combination of both\n TransactionHeader values passed in as keyword arguments, and defaults\n set on TransactionEncoder.\n\n Args:\n payload (bytes): If no payload_encoder is set on the\n TransactionEncoder, the payload must be byte-encoded\n batcher_public_key (string or bytes, optional): Batcher public key\n dependencies (list of str, optional): Transaction ids that must be\n committed before this Transaction\n family_name (str, optional): Name of Transaction Family\n family_version (str, optional): Version of Transaction Family\n inputs (list of str, optional): State addresses that Transaction\n created by this encoder will read from\n nonce (str, optional): Random string to ensure uniqueness\n outputs (list of str, optional): State addresses that Transaction\n created by this encoder will write to\n\n Raises:\n TypeError: Raised if a user-supplied required header was not set\n in either the TransactionEncoder, or during this method call.\n Required user-supplied headers include:\n * family_name\n * family_version\n * inputs\n * outputs\n\n Returns:\n Transaction: A signed Transaction Protobuf message\n \"\"\"\n payload = self.payload_encoder(payload)\n payload_sha512 = sha512(payload).hexdigest()\n\n def resolve_required(key, value):\n value = value if value is not None else getattr(self, key)\n if value is None:\n raise TypeError('\"{}\" must be set in the TransactionEncoder '\n 'or as a keyword argument'.format(key))\n return value\n\n txn_header = TransactionHeader(\n family_name=resolve_required('family_name', family_name),\n family_version=resolve_required('family_version', family_version),\n inputs=resolve_required('inputs', inputs),\n outputs=resolve_required('outputs', outputs),\n batcher_public_key=(batcher_public_key if batcher_public_key is not\n None else self.batcher_public_key),\n dependencies=(dependencies if dependencies is not None\n else self.dependencies),\n nonce=nonce if nonce is not None else str(randint(0, 100000000)),\n payload_sha512=payload_sha512,\n signer_public_key=self._public_key)\n\n header_bytes = txn_header.SerializeToString()\n return Transaction(\n header=header_bytes,\n header_signature=sign(header_bytes,\n self._private_key,\n private_key_format='bytes'),\n payload=payload)\n\n def encode(self, transactions):\n \"\"\"Wraps one or more Transaction messages in a TransactionList and\n serializes it for transmission to a batcher.\n\n Args:\n transactions (list of Transaction or Transaction): The Transaction\n or Transactions to wrap in a TransactionList\n\n Returns:\n bytes: a serialized TransactionList\n \"\"\"\n transactions = _listify(transactions)\n txn_list = TransactionList(transactions=transactions)\n return txn_list.SerializeToString()\n\n def create_encoded(self,\n payload,\n batcher_public_key=None,\n dependencies=None,\n family_name=None,\n family_version=None,\n inputs=None,\n nonce=None,\n outputs=None):\n \"\"\"Convenience method which creates a single Transaction from a payload\n and supplied or default TransactionHeader values, before wrapping it\n in a TransactionList and serializing it. Accepts identical parameters\n to TransactionEncoder.create().\n\n Args:\n payload (bytes): If no payload_encoder is set on the\n TransactionEncoder, the payload must be byte-encoded\n batcher_public_key (string or bytes, optional): Batcher public key\n dependencies (list of str, optional): Transaction ids that must be\n committed before this Transaction\n family_name (str, optional): Name of Transaction Family\n family_version (str, optional): Version of Transaction Family\n inputs (list of str, optional): State addresses that Transaction\n created by this encoder will read from\n nonce (str, optional): Random string to ensure uniqueness\n outputs (list of str, optional): State addresses that Transaction\n created by this encoder will write to\n\n Raises:\n TypeError: Raised if a user-supplied required header was not set\n in either the TransactionEncoder, or during this method call.\n Required user-supplied headers include:\n * family_name\n * family_version\n * inputs\n * outputs\n\n Returns:\n bytes: a serialized TransactionList\n \"\"\"\n txn = self.create(payload,\n batcher_public_key=batcher_public_key,\n dependencies=dependencies,\n family_name=family_name,\n family_version=family_version,\n inputs=inputs,\n nonce=nonce,\n outputs=outputs)\n return self.encode(txn)\n\n\nclass BatchEncoder(object):\n \"\"\"Stores a private key which can be used to create and sign Batches of\n Transactions.\n\n Args:\n private_key (bytes): The private key to sign Batches with\n \"\"\"\n def __init__(self, private_key):\n self._private_key = private_key\n self._public_key = generate_public_key(\n private_key, private_key_format='bytes')\n\n def create(self, transactions):\n \"\"\"Creates and signs a new Batch message with one or more Transactions.\n Transactions can be input as Transaction instances or as a serialized\n TransactionList.\n\n Args:\n transactions (bytes or Transaction or list of Transaction):\n The Transactions to wrap in this Batch.\n\n Returns:\n Batch: A signed Transaction Protobuf message\n \"\"\"\n try:\n txn_list = TransactionList()\n txn_list.ParseFromString(transactions)\n transactions = txn_list.transactions\n except (TypeError, DecodeError):\n transactions = _listify(transactions)\n\n batch_header = BatchHeader(\n signer_public_key=self._public_key,\n transaction_ids=[t.header_signature for t in transactions])\n header_bytes = batch_header.SerializeToString()\n\n return Batch(\n header=header_bytes,\n header_signature=sign(header_bytes,\n self._private_key,\n private_key_format='bytes'),\n transactions=transactions)\n\n def encode(self, batches):\n \"\"\"Wraps one or more Batch messages in a BatchList and serializes it\n for transmission to a validator.\n\n Args:\n batches (list of Batch or Batch): The Batch or Batches to wrap in\n a BatchList\n\n Returns:\n bytes: a serialized BatchList\n \"\"\"\n batches = _listify(batches)\n batch_list = BatchList(batches=batches)\n return batch_list.SerializeToString()\n\n def create_encoded(self, transactions):\n \"\"\"Convenience method which creates a single Batch from a Transaction\n or Transactions, before wrapping it in a BatchList and serializing it.\n Accepts identical parameters to BatchEncoder.create().\n\n Args:\n transactions (bytes or Transaction or list of Transaction):\n The Transactions to wrap in this Batch. Can be formatted as\n a serialized TransactionList, a single Transaction instance, or\n a list of Transaction instances.\n\n Returns:\n bytes: a serialized BatchList\n \"\"\"\n batch = self.create(transactions)\n return self.encode(batch)\n","sub_path":"sdk/python/sawtooth_sdk/client/encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":12416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"263358031","text":"\"\"\"\n## Problem1 Populating Next Right Pointers in Each Node(https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)\n\nYou are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the\nfollowing definition:\n\nstruct Node {\n\n int val;\n\n Node *left;\n\n Node *right;\n\n Node *next;\n\n}\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\n\nInitially, all next pointers are set to NULL.\n\nExample:\n\n\n\nInput: {\"$id\":\"1\",\"left\":{\"$id\":\"2\",\"left\":{\"$id\":\"3\",\"left\":null,\"next\":null,\"right\":null,\"val\":4},\"next\":null,\"right\":{\"$id\":\"4\",\"left\":null,\"next\":null,\"right\":null,\"val\":5},\"val\":2},\"next\":null,\"right\":{\"$id\":\"5\",\"left\":{\"$id\":\"6\",\"left\":null,\"next\":null,\"right\":null,\"val\":6},\"next\":null,\"right\":{\"$id\":\"7\",\"left\":null,\"next\":null,\"right\":null,\"val\":7},\"val\":3},\"val\":1}\n\nOutput: {\"$id\":\"1\",\"left\":{\"$id\":\"2\",\"left\":{\"$id\":\"3\",\"left\":null,\"next\":{\"$id\":\"4\",\"left\":null,\"next\":{\"$id\":\"5\",\"left\":null,\"next\":{\"$id\":\"6\",\"left\":null,\"next\":null,\"right\":null,\"val\":7},\"right\":null,\"val\":6},\"right\":null,\"val\":5},\"right\":null,\"val\":4},\"next\":{\"$id\":\"7\",\"left\":{\"$ref\":\"5\"},\"next\":null,\"right\":{\"$ref\":\"6\"},\"val\":3},\"right\":{\"$ref\":\"4\"},\"val\":2},\"next\":null,\"right\":{\"$ref\":\"7\"},\"val\":1}\n\nExplanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right\nnode, just like in Figure B.\n\nNote:\n\nYou may only use constant extra space.\n\nRecursive approach is fine, implicit stack space does not count as extra space for this problem.\n\n\n\"\"\"\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\n#TIME- O(N)\n#SPACE- CONSTANT\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if root == None:\n return\n temp = root\n while temp != None:\n curr = temp\n while curr != None:\n if curr.left:\n curr.left.next = curr.right\n if curr.right and curr.next:\n curr.right.next = curr.next.left\n\n curr = curr.next\n\n temp = temp.left\n return root\n\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\n#TIME- O(N)\n#SPACE- O(N)\nfrom collections import deque\n\n\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if root == None:\n return\n q = deque()\n q.append(root)\n while q:\n size = len(q)\n prev = q.popleft()\n if prev.left:\n q.append(prev.left)\n if prev.right:\n q.append(prev.right)\n for i in range(1, size):\n curr = q.popleft()\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n prev.next = curr\n prev = curr\n\n return root\n\n#RECURSION\nclass Solution:\n def connect(self, root: 'Node') -> 'Node':\n if root == None:\n return\n self.dfs(root)\n return root\n\n def dfs(self, root):\n if root == None:\n return\n if root.left:\n root.left.next = root.right\n\n if root.right and root.next:\n root.right.next = root.next.left\n self.dfs(root.left)\n self.dfs(root.right)\n\n","sub_path":"nxtRightPointers.py","file_name":"nxtRightPointers.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"357906011","text":"# Kolbeinn Ingólfsson\n# 12.2.2018\n# Klasar fyrir Skil02\n\nimport pygame\nfrom random import *\n\nsprengjur = []\nvarnir = []\nveggir = []\nendir = []\n\n\ndef radius():\n return randint(5, 8)\n\n\nclass Player(object):\n def __init__(self):\n self.rect = pygame.Rect(16, 16, 16, 16)\n self.fjVarna = 0\n self.ovirkarSprengjur = 0\n self.stig = 0\n\n def move(self, dx, dy):\n if dx != 0:\n self.move_single_axis(dx, 0)\n if dy != 0:\n self.move_single_axis(0, dy)\n\n def anti(self):\n return self.fjVarna\n\n def draw(self):\n if self.fjVarna > 0:\n spilari = (255, 200, 0)\n else:\n spilari = (255, 128, 0)\n return spilari\n\n def move_single_axis(self, dx, dy):\n self.rect.x += dx\n self.rect.y += dy\n\n for veggur in veggir:\n if self.rect.colliderect(veggur.rect):\n if dx > 0:\n self.rect.right = veggur.rect.left\n if dx < 0:\n self.rect.left = veggur.rect.right\n if dy > 0:\n self.rect.bottom = veggur.rect.top\n if dy < 0:\n self.rect.top = veggur.rect.bottom\n\n for e in range(0, len(endir), 2):\n if endir[e+1] == 0:\n if self.rect.colliderect(endir[e].rect):\n if dx > 0:\n self.rect.right = endir[e].rect.left\n if dx < 0:\n self.rect.left = endir[e].rect.right\n if dy > 0:\n self.rect.bottom = endir[e].rect.top\n if dy < 0:\n self.rect.top = endir[e].rect.bottom\n\n\n for sprengja in sprengjur:\n if self.rect.colliderect(sprengja.rect):\n if self.fjVarna >= 1:\n if dx > 0:\n self.rect.right = sprengja.rect.left\n sprengjur.remove(sprengja)\n self.ovirkarSprengjur += 1\n self.fjVarna -= 1\n self.stig += 5\n if dx < 0:\n self.rect.left = sprengja.rect.right\n sprengjur.remove(sprengja)\n self.ovirkarSprengjur += 1\n self.fjVarna -= 1\n self.stig += 5\n if dy > 0:\n self.rect.bottom = sprengja.rect.top\n sprengjur.remove(sprengja)\n self.ovirkarSprengjur += 1\n self.fjVarna -= 1\n self.stig += 5\n if dy < 0:\n self.rect.top = sprengja.rect.bottom\n sprengjur.remove(sprengja)\n self.ovirkarSprengjur += 1\n self.fjVarna -= 1\n self.stig += 5\n else:\n raise SystemExit(\"BOOM!\")\n\n\n if dx > 0:\n self.rect.right = sprengja.rect.left\n if dx < 0:\n self.rect.left = sprengja.rect.right\n if dy > 0:\n self.rect.bottom = sprengja.rect.top\n if dy < 0:\n self.rect.top = sprengja.rect.bottom\n\n for vorn in varnir:\n if self.rect.colliderect(vorn.rect):\n if dx > 0:\n self.fjVarna += 1\n varnir.remove(vorn)\n if dx < 0:\n self.fjVarna += 1\n varnir.remove(vorn)\n if dy > 0:\n self.fjVarna += 1\n varnir.remove(vorn)\n if dy < 0:\n self.fjVarna += 1\n varnir.remove(vorn)\n\n\nclass Sprengja(object):\n\n def __init__(self, pos):\n sprengjur.append(self)\n self.rect = pygame.Rect(pos[0], pos[1], 16, 16)\n\n\nclass SprengjuVarnir(object):\n\n def __init__(self, pos):\n varnir.append(self)\n self.rect = pygame.Rect(pos[0], pos[1], 16, 16)\n\n\nclass Veggur(object):\n def __init__(self, pos):\n veggir.append(self)\n self.rect = pygame.Rect(pos[0], pos[1], 16, 16)\n\n\nclass Endir(object):\n def __init__(self, pos, rg):\n if rg == 1:\n global endir\n endir = []\n endir.append(self)\n endir.append(rg)\n self.rect = pygame.Rect(pos[0], pos[1], 16, 16)\n\n","sub_path":"Skil02/klasar.py","file_name":"klasar.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"441786858","text":"from django.conf.urls import patterns, url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom form.views import StatusArrivalUpdate, StatusDepartureUpdate, AssignedReception, AssignedDispatch\n\nurlpatterns = patterns('form.views',\n url(r'^cancel_arrival/$', StatusArrivalUpdate.as_view(), name='cancel_arrival'),\n url(r'^cancel_departure/$', StatusDepartureUpdate.as_view(), name='cancel_departure'),\n url(r'^assigned_arrival/$', AssignedReception.as_view(), name='assigned_arrival'),\n url(r'^assigned_departure/$', AssignedDispatch.as_view(), name='assigned_departure'),\n )\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"form/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"649959101","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport pyexcel\nfrom recipedb import Recipe\nimport mlab\nimport requests\n\nmlab.connect()\n\nfor n in range(1,1000):\n data = requests.get(\"https://www.cooky.vn/directory/search?q=null&st=2&lv=&cs=&cm=&dt=&igt=&oc=&p=&crs=&page=\"+ str(n) + \"&pageSize=12&append=true&video=false\").json()\n url = str(\"https://www.cooky.vn\") + data[\"recipes\"][1][\"DetailUrl\"]\n ingredients = []\n d={}\n steps_list = []\n s={}\n ingredients_name = []\n try:\n item_url = urlopen(url)\n raw = item_url.read()\n web_text = raw.decode(\"utf-8\")\n recipe_soup = BeautifulSoup(web_text,\"html.parser\")\n #get name\n name_list = recipe_soup.find(\"h1\",\"p-name fn recipe-title \")\n recipe_name = name_list.string\n #get image\n image_list = recipe_soup.find(\"div\", \"recipe-header-photo\")\n recipe_image = image_list.img[\"src\"]\n #get ingredients\n recipe_ingredient = recipe_soup.find('ul', 'list-inline recipe-ingredient-list')\n ingredient_list = recipe_ingredient.find_all(\"li\",\"ingredient\") \n for item in ingredient_list:\n name = item.find(\"span\", \"name\").string\n amount = item.find(\"span\", \"ingredient-quality\").string\n amount = amount.replace(\"\",\"\").replace(\"\",\"\").replace(\"\",\"\").replace(\"\",\"\").strip()\n unit = item.find(\"span\",\"ingredient-unit\").string\n d[\"name\"]=name\n d[\"amount\"]=amount\n d[\"unit\"]=unit\n ingredients_name.append(name)\n ingredients.append(d.copy())\n #get steps\n steps_area = recipe_soup.find(\"div\", id=\"accordionDirection\")\n steps = steps_area.find_all(\"div\", \"panel panel-default clearfix\")\n for item in steps:\n step_text = item.find(\"div\", \"step-desc\").string\n step_image = item.find(\"div\", \"step-photos\").a.img[\"data-src\"]\n s[\"text\"] = step_text\n s[\"image\"] = step_image\n steps_list.append(s.copy())\n #get duration:\n duration_list = recipe_soup.find(\"span\",\"value-title\")[\"title\"]\n duration = duration_list.replace(\"PT\",\"\")\n #get number of ingredients:\n ingredient_count = len(ingredients)\n #get level:\n ul = recipe_soup.find(\"ul\",\"list-inline nomargin nopadding\")\n list_of_li = ul.find_all(\"li\")\n level = list_of_li[3].find(\"b\",\"stats-count\").string\n #save to DB:\n i=Recipe(recipe_name=recipe_name,recipe_image=recipe_image,ingredients=ingredients,steps=steps_list,duration=duration,level=level,ingredient_count=ingredient_count,ingredients_name=ingredients_name)\n i.save()\n \n except:\n pass\n\n","sub_path":"recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"163638055","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 2 19:33:49 2019\n\n@author: hariguragain\n\"\"\"\n\nclass Settings():\n \"\"\" A class to store all settings for Alien Invasion\"\"\"\n \n \n def __init__(self):\n \"\"\"Initialize the game's settings.\"\"\"\n #Screen Settings\n self.screen_width = 1000\n self.screen_height = 700\n self.bg_color = (230, 230, 230)\n ","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394165604","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"e2e-Dutch\",\n version=\"0.0.1\",\n author=\"Dafne van Kuppevelt\",\n author_email=\"d.vankuppevelt@esciencecenter.nl\",\n description=\"Coreference resolution with e2e for Dutch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Filter-Bubble/e2e-Dutch\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 4 - Beta\",\n \"Environment :: Console\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n ],\n include_package_data=True,\n package_data={#('cfg', ['cfg/*']),\n 'e2edutch': ['lib/coref_kernels.so',\n 'cfg/*.conf']},\n test_suite='test',\n python_requires='>=3.6',\n install_requires=[\n \"tensorflow>=2.0.0\",\n \"h5py\",\n \"nltk\",\n \"pyhocon\",\n \"scipy\",\n \"scikit-learn\",\n \"torch\",\n \"transformers\"\n ],\n tests_require=[\n 'pytest',\n 'pytest-cov',\n 'pycodestyle',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"94206195","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic.list import ListView\nfrom Contact.forms import ContactForm\n\nfrom Contact.models import Contact\n\ndef index(request):\n contacts = Contact.objects.all()\n context ={'contacts':contacts}\n context['form'] = ContactForm()\n if request.method ==\"POST\":\n\n form = ContactForm(request.POST)\n\n if form.is_valid():\n data = form.cleaned_data\n contact=Contact.objects.create(**data)\n contact.save()\n return render(request,'contacts/index.html',context)\n\n return render(request,'contacts/index.html',context)\n\n\n\n","sub_path":"Contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"49874011","text":"import tweepy, sys, random, pickle\n\ntry:\n\t#Twitter credentials\n\tCONSUMER_KEY = 'YOUR_CONSUMER_KEY'\n\tCONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'\n\tACCESS_KEY = 'YOUR_ACCESS_KEY'\n\tACCESS_SECRET = 'YOUR_ACCESS_SECRET'\n\n\t#Setting up the authentication and API for Twitter\n\tauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n\tauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\n\tapi = tweepy.API(auth)\n\n\tdef main():\n\t\t#If using cron job, the path must be placed manually\n\t\tnumberOfNouns = sum(1 for line in open('finnishnouns.txt', 'r'))\n\t\t\t\n\t\t#Create a pickle file for maintaining already used nouns\n\t\tpickle_file = open('nounfile.pickle', 'ab')\n\t\ttry:\n\t\t\tusedNouns = pickle.load(open('nounfile.pickle', 'rb'))\n\t\texcept EOFError:\n\t\t\tusedNouns = []\n\n\t\t#Get a random noun\n\t\tnounIndex = random.randint(0, numberOfNouns-1)\n\t\twhile nounIndex in usedNouns:\n\t\t\tnounIndex = random.randint(0, numberOfNouns-1)\n\t\t\n\t\t#If using cron job, the path must be placed manually\n\t\tnoun = open('finnishnouns.txt', 'r').readlines()[nounIndex].strip()\n\n\t\t#Check if the noun has already been tweeted\n\t\tif len(usedNouns) < numberOfNouns:\n\t\t\tusedNouns.append(nounIndex)\n\t\t\twith open ('nounfile.pickle', 'wb') as pickle_file:\n\t\t\t\tpickle.dump(usedNouns, pickle_file)\n\n\t\t#Form the tweet\n\t\ttweet = noun + \" on pilalla\"\n\t\t\t\n\t\tapi.update_status(tweet)\n\n\tif __name__ == \"__main__\":\n\t\tmain()\n\t\t\nexcept Exception as e:\n print(e)","sub_path":"pilallabot.py","file_name":"pilallabot.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"153698429","text":"\nimport os\nimport datetime\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\nfrom pontoon.administration.views import _update_from_repository\nfrom pontoon.base.models import Project\n\n\nclass Command(BaseCommand):\n help = 'Update all projects from their repositories and store changes \\\n to the database'\n\n def handle(self, *args, **options):\n for project in Project.objects.all():\n try:\n repository_type = project.repository_type\n repository_url = project.repository_url\n repository_path_master = os.path.join(\n settings.MEDIA_ROOT, repository_type, project.slug)\n\n _update_from_repository(\n project, repository_type, repository_url,\n repository_path_master)\n now = datetime.datetime.now()\n self.stdout.write(\n '[%s]: Successfully updated project \"%s\"\\n' %\n (now, project))\n except Exception as e:\n now = datetime.datetime.now()\n raise CommandError(\n '[%s]: UpdateProjectsFromRepositoryError: %s\\n' %\n (now, unicode(e)))\n","sub_path":"pontoon/administration/management/commands/update_projects.py","file_name":"update_projects.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"2080433","text":"import glob, shutil, os\nfrom os.path import join, basename, dirname, isfile, isdir, splitext\n\n#rootdir = '/home/jasper/data/bbc/meg/'\nrootdir = '/diskArray/data/bbc/meg/'\nheadposdir = join(rootdir, 'eval', 'headpos')\nif not isdir(headposdir):\n os.makedirs(headposdir)\n\nsubjectdirs = glob.glob(join(rootdir, 'bbc_*'))\nfor s, subjectdir in enumerate(subjectdirs):\n subject = basename(subjectdir)\n print('Subject {} of {}: {}'.format(s+1, len(subjectdirs), subject))\n\n shutil.copyfile(join(subjectdir , 'headpos.log'), \n join(headposdir, subject+'_headpos.log'))\n","sub_path":"mmimproc/projects/bbc/meg/eval_headpos.py","file_name":"eval_headpos.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"646552202","text":"class Shape:\n def __init__(self, w, l):\n self.width = w\n self.length = l\n\n def calculate_perimeter(self):\n return self.width + self.length\n\n def what_am_i(self):\n print(\"I am a shape\")\n\nclass Rectangle(Shape):\n pass\n\nclass Square(Shape):\n def change_size(self, c):\n self.width += c\n self.length += c\n\nclass Horse:\n def __init__(self, name, rider):\n self.name = name\n self.rider = rider\n\nclass Rider:\n def __init__(self, name):\n self.name = name\n\nrectangle = Rectangle(5, 3)\nsquare = Square(4, 4)\n\nprint(rectangle.calculate_perimeter())\nprint(square.calculate_perimeter())\n\nsquare.change_size(5)\nprint(square.calculate_perimeter())\n\nsquare.change_size(-1)\nprint(square.calculate_perimeter())\n\nsquare.what_am_i()\n\nmick = Rider(\"Mick Jagger\")\nstan = Horse(\"Stanley\", mick)\nprint(stan.rider.name)\n","sub_path":"challenge_13.py","file_name":"challenge_13.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"59725060","text":"\n\nfrom xai.brain.wordbase.nouns._gurney import _GURNEY\n\n#calss header\nclass _GURNEYS(_GURNEY, ):\n\tdef __init__(self,): \n\t\t_GURNEY.__init__(self)\n\t\tself.name = \"GURNEYS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"gurney\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_gurneys.py","file_name":"_gurneys.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"327797928","text":"target = int(input())\n#자릿수 파악\na = list(str(target))\n\n#분해합 계산\ndef dgit(num):\n a = map(int, list(str(num)))\n return (num + sum(a))\n\n#자릿수마다 최대 9까지 더해질 수 있으므로, 이에따라 반복 범위를 제한할 수 있음\n#시간제한이 있어서 1부터 루프를 돌리면 실패\n\n#i값이 음수부터 시작하지 않도록 1~18, 나머지로 범위를 나눔\nif target >= 19:\n for i in range(target - (len(a) * 9), target):\n if target == dgit(i):\n print(i)\n break\n if i == target-1:\n print(0)\nelse:\n for i in range(0, target):\n if target == dgit(i):\n print(i)\n if i == target-1:\n print(0)\n","sub_path":"hiseoung/BOJ/그리디/20210202_boj_2231_분해합.py","file_name":"20210202_boj_2231_분해합.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"153188528","text":"from snovault import (\n calculated_property,\n collection,\n load_schema,\n)\nfrom .base import (\n Item,\n # SharedItem,\n paths_filtered_by_status,\n)\nimport re\n\n\n@collection(\n name=\"fvp_b1s\",\n unique_key=\"uuid\",\n properties={\n \"title\": \"UDS_FVP_B1 Forms\",\n \"description\": \"NACC Uniform Data Set (UDS) - FOLLOW-UP FORM B1: EVALUATION FORM - PHYSICAL\",\n },\n)\nclass Fvp_b1(Item):\n item_type = \"fvp_b1\"\n schema = load_schema(\"encoded:schemas/fvp_b1.json\")\n embedded = [\n ]\n rev = {\n }\n audit_inherit = []\n set_status_up = []\n set_status_down = []","sub_path":"src/encoded/types/fvp_b1.py","file_name":"fvp_b1.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"653210925","text":"import torch\nimport torch.nn as nn\nfrom torch.distributions import Categorical\n\n\nclass LSTMModel(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(LSTMModel, self).__init__()\n\n self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size)\n self.fc = nn.Linear(hidden_size, output_size)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, X):\n outputs, _ = self.lstm(X)\n outputs = self.fc(outputs.view(-1, outputs.shape[-1]))\n return outputs\n\n def sample(self, X, do_argmax=False):\n outputs, _ = self.lstm(X)\n outputs = self.fc(outputs.view(-1, outputs.shape[-1]))\n if not do_argmax:\n m = Categorical(probs=self.softmax(outputs[-1].view(1, -1)))\n return m.sample()\n else:\n return torch.argmax(outputs, 1)[-1]","sub_path":"Models/LSTMBased.py","file_name":"LSTMBased.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"156869089","text":"def add(a , b):\n print(f\"ADDING {a} + {b}\")\n return a + b\n\ndef subtract(a , b):\n print(f\"SUBTRACTING {a} - {b}\")\n return a - b\n\ndef multiply(a , b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a * b\n\ndef devide(a, b):\n print(f\"Deviding {a} / {b}\")\n return a / b\n\nprint(\"Let's do some math with just functions!\")\n\nage = add(12 , 24)\nheight = subtract(30 , 5)\nweight = multiply(100 , 3)\niq = devide(50 , 2)\n\nprint(f\"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}\")\n\n# A puzzle for the extra credit , type it anyway\nprint(\"Here is a puzzle\")\n\n# age + (height - (weight * (iq / 2))) \nwhat = add(age, subtract(height , multiply(weight , devide(iq , 2))))\n\nprint(\"That becomes : \", what , \"Can you do it with it by hand?\")","sub_path":"ex21/ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"243194693","text":"popA = int (input(\"Número de habitantes de uma cidade A: \"))\npopB = int (input(\"Número de habitantes de uma cidade B: \"))\ncresA = float (input(\"Percentual de crescimento populacional da cidade A: \"))\ncresB = float (input(\"Percentual de crescimento populacional da cidade B: \"))\n\nsoma=1\n\nwhile(popA < popB):\n\tpopA = popA +(popA*cresA/100)\n\tpopB = popB +(popB*cresB/100)\n\tsoma= soma + 1\nprint(soma)\n\t\n\t","sub_path":"exs/1403-1136.py","file_name":"1403-1136.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"534219927","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport argparse\nimport datetime\nimport time\nimport copy\nimport sqlite3\nfrom multiprocessing import Process\n\n# Import openlavaMonitor packages.\nif ('openlavaMonitor_development_path' in os.environ) and os.path.exists(os.environ['openlavaMonitor_development_path']):\n sys.path.insert(0, os.environ['openlavaMonitor_development_path'])\n\nfrom monitor.conf import config\nfrom monitor.common import common\n\nos.environ[\"PYTHONUNBUFFERED\"]=\"1\"\n\ndef readArgs():\n \"\"\"\n Read arguments.\n \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-j\", \"--job\",\n action=\"store_true\", default=False,\n help='Sample running job info with command \"bjobs -u all -r -UF\".')\n parser.add_argument(\"-q\", \"--queue\",\n action=\"store_true\", default=False,\n help='Sample queue info with command \"bqueues\".')\n parser.add_argument(\"-H\", \"--host\",\n action=\"store_true\", default=False,\n help='Sample host info with command \"bhosts\".')\n parser.add_argument(\"-l\", \"--load\",\n action=\"store_true\", default=False,\n help='Sample host load info with command \"lsload\".')\n parser.add_argument(\"-u\", \"--user\",\n action=\"store_true\", default=False,\n help='Sample user info with command \"busers\".')\n parser.add_argument(\"-i\", \"--interval\",\n type=int,\n default=0,\n help='Specify the sampling interval, unit is second. Sampling only once by default\".')\n\n args = parser.parse_args()\n\n if args.interval < 0:\n common.printError('*Error*: interval \"' + str(args.interval) + '\": Cannot be less than \"0\".')\n sys.exit(1)\n\n return(args.job, args.queue, args.host, args.load, args.user, args.interval)\n\nclass sampling:\n \"\"\"\n Sample openlava basic information with openlava bjobs/bqueues/bhosts/lshosts/lsload/busers commands.\n Save the infomation into sqlite3 DB.\n \"\"\"\n def __init__(self, jobSampling, queueSampling, hostSampling, loadSampling, userSampling, interval):\n self.jobSampling = jobSampling\n self.queueSampling = queueSampling\n self.hostSampling = hostSampling\n self.loadSampling = loadSampling\n self.userSampling = userSampling\n\n self.interval = interval\n self.dbPath = config.dbPath\n\n def getDateInfo(self):\n self.currentDate = datetime.datetime.today().strftime('%Y%m%d')\n self.currentTime = datetime.datetime.today().strftime('%H%M%S')\n self.currentSeconds = int(time.time())\n\n def addKeyDateInfo(self, inputKeyList):\n \"\"\"\n Insert date info into key list.\n \"\"\"\n keyList = copy.deepcopy(inputKeyList)\n keyList.insert(0, 'sampleTime')\n keyList.insert(1, 'DATE')\n keyList.insert(2, 'TIME')\n keyList.insert(3, 'SECONDS')\n return(keyList)\n\n def addValueDateInfo(self, inputValueList):\n \"\"\"\n Insert date info into value list.\n \"\"\"\n valueList = copy.deepcopy(inputValueList)\n valueList.insert(0, str(self.currentDate) + '_' + str(self.currentTime))\n valueList.insert(1, self.currentDate)\n valueList.insert(2, self.currentTime)\n valueList.insert(3, self.currentSeconds)\n return(valueList)\n\n def sampleJobInfo(self):\n \"\"\"\n Sample job info, especially the memory usage info.\n \"\"\"\n self.getDateInfo()\n self.jobDbFile = str(self.dbPath) + '/job.db'\n self.jobDbConn = sqlite3.connect(self.jobDbFile)\n self.jobDbCurs = self.jobDbConn.cursor()\n\n print('>>> Sampling job info into ' + str(self.jobDbFile) + ' ...')\n\n jobTableList = common.getSqlTableList(self.jobDbFile, self.jobDbCurs)\n bjobsDic = common.getBjobsUfInfo()\n jobList = list(bjobsDic.keys())\n\n for job in jobList:\n jobTableName='job_' + str(job)\n print(' Sampling for job \"' + str(job) + '\" ...')\n\n # Insert 'sampleTime', 'DATE', 'TIME' and 'SECONDS' into key list.\n jobDic = bjobsDic[job]\n keyList = list(jobDic.keys())\n valueList = list(jobDic.values())\n valueList = self.addValueDateInfo(valueList)\n\n # If job table (with old data) has been on the self.jobDbFile, drop it.\n if jobTableName in jobTableList:\n dataDic = common.getSqlTableData(self.jobDbFile, self.jobDbCurs, jobTableName, ['SECONDS'])\n if dataDic:\n if len(dataDic['SECONDS']) > 0:\n lastSeconds = int(dataDic['SECONDS'][-1])\n if self.currentSeconds-lastSeconds > 864000:\n common.printWarning('*Warning*: table \"' + str(jobTableName) + '\" already existed even ten day ago, will drop it.')\n common.dropSqlTable(self.jobDbFile, self.jobDbCurs, jobTableName)\n\n # If job table is not on the self.jobDbFile, create it.\n if jobTableName not in jobTableList:\n keyList = self.addKeyDateInfo(keyList)\n keyString = common.genSqlTableKeyString(keyList)\n common.createSqlTable(self.jobDbFile, self.jobDbConn, jobTableName, keyString)\n\n # Insert sql table value.\n valueString = common.genSqlTableValueString(valueList)\n common.insertIntoSqlTable(self.jobDbFile, self.jobDbConn, jobTableName, valueString)\n\n self.jobDbCurs.close()\n self.jobDbConn.close()\n\n def sampleQueueInfo(self):\n \"\"\"\n Sample queue info and save it into sqlite db.\n \"\"\"\n self.getDateInfo()\n self.queueDbFile = str(self.dbPath) + '/queue.db'\n self.queueDbConn = sqlite3.connect(self.queueDbFile)\n self.queueDbCurs = self.queueDbConn.cursor()\n\n print('>>> Sampling queue info into ' + str(self.queueDbFile) + ' ...')\n\n queueTableList = common.getSqlTableList(self.queueDbFile, self.queueDbCurs)\n bqueuesDic = common.getBqueuesInfo()\n queueList = bqueuesDic['QUEUE_NAME']\n queueHostDic = common.getQueueHostInfo()\n\n # Insert 'sampleTime', 'DATE', 'TIME' and 'SECONDS' into key list.\n origKeyList = list(bqueuesDic.keys())\n keyList = self.addKeyDateInfo(origKeyList)\n keyList.append('HOST')\n\n for i in range(len(queueList)):\n queue = queueList[i]\n queueTableName = 'queue_' + str(queue)\n print(' Sampling for queue \"' + str(queue) + '\" ...')\n\n # Get the queue value infos.\n valueList = []\n valueList = self.addValueDateInfo(valueList)\n for key in origKeyList:\n keyValue = bqueuesDic[key][i]\n valueList.append(keyValue)\n\n # Add queue-host info into queue value infos.\n queueHosts = queueHostDic[queue]\n hostString = ' '.join(queueHosts)\n valueList.append(hostString)\n\n # Generate sql table.\n if queueTableName not in queueTableList:\n keyString = common.genSqlTableKeyString(keyList)\n common.createSqlTable(self.queueDbFile, self.queueDbConn, queueTableName, keyString)\n\n # Insert sql table value.\n valueString = common.genSqlTableValueString(valueList)\n common.insertIntoSqlTable(self.queueDbFile, self.queueDbConn, queueTableName, valueString)\n\n self.queueDbCurs.close()\n self.queueDbConn.close()\n\n def sampleHostInfo(self):\n \"\"\"\n Sample host info and save it into sqlite db.\n \"\"\"\n self.getDateInfo()\n self.hostDbFile = str(self.dbPath) + '/host.db'\n self.hostDbConn = sqlite3.connect(self.hostDbFile)\n self.hostDbCurs = self.hostDbConn.cursor()\n\n print('>>> Sampling host info into ' + str(self.hostDbFile) + ' ...')\n\n hostTableList = common.getSqlTableList(self.hostDbFile, self.hostDbCurs)\n bhostsDic = common.getBhostsInfo()\n hostList = bhostsDic['HOST_NAME']\n\n # Insert 'sampleTime', 'DATE', 'TIME' and 'SECONDS' into key list.\n origKeyList = list(bhostsDic.keys())\n keyList = self.addKeyDateInfo(origKeyList)\n\n for i in range(len(hostList)):\n host = hostList[i]\n hostTableName = 'host_' + str(host)\n print(' Sampling for host \"' + str(host) + '\" ...')\n\n # Get the host value infos.\n valueList = []\n valueList = self.addValueDateInfo(valueList)\n for key in origKeyList:\n keyValue = bhostsDic[key][i]\n valueList.append(keyValue)\n\n # Generate sql table.\n if hostTableName not in hostTableList:\n keyString = common.genSqlTableKeyString(keyList)\n common.createSqlTable(self.hostDbFile, self.hostDbConn, hostTableName, keyString)\n\n # Insert sql table value.\n valueString = common.genSqlTableValueString(valueList)\n common.insertIntoSqlTable(self.hostDbFile, self.hostDbConn, hostTableName, valueString)\n\n self.hostDbCurs.close()\n self.hostDbConn.close()\n\n def sampleLoadInfo(self):\n \"\"\"\n Sample host load info and save it into sqlite db.\n \"\"\"\n self.getDateInfo()\n self.loadDbFile = str(self.dbPath) + '/load.db'\n self.loadDbConn = sqlite3.connect(self.loadDbFile)\n self.loadDbCurs = self.loadDbConn.cursor()\n\n print('>>> Sampling host load info into ' + str(self.loadDbFile) + ' ...')\n\n loadTableList = common.getSqlTableList(self.loadDbFile, self.loadDbCurs)\n lsloadDic = common.getLsloadInfo()\n hostList = lsloadDic['HOST_NAME']\n\n # Insert 'sampleTime', 'DATE', 'TIME' and 'SECONDS' into key list.\n origKeyList = list(lsloadDic.keys())\n keyList = self.addKeyDateInfo(origKeyList)\n\n for i in range(len(hostList)):\n host = hostList[i]\n loadTableName = 'host_' + str(host)\n print(' Sampling for host \"' + str(host) + '\" ...')\n\n # Get the host load value infos.\n valueList = []\n valueList = self.addValueDateInfo(valueList)\n for key in origKeyList:\n keyValue = lsloadDic[key][i]\n valueList.append(keyValue)\n\n # Generate sql table.\n if loadTableName not in loadTableList:\n keyString = common.genSqlTableKeyString(keyList)\n common.createSqlTable(self.loadDbFile, self.loadDbConn, loadTableName, keyString)\n\n # Insert sql table value.\n valueString = common.genSqlTableValueString(valueList)\n common.insertIntoSqlTable(self.loadDbFile, self.loadDbConn, loadTableName, valueString)\n\n self.loadDbCurs.close()\n self.loadDbConn.close()\n\n def sampleUserInfo(self):\n \"\"\"\n Sample user info and save it into sqlite db.\n \"\"\"\n self.getDateInfo()\n self.userDbFile = str(self.dbPath) + '/user.db'\n self.userDbConn = sqlite3.connect(self.userDbFile)\n self.userDbCurs = self.userDbConn.cursor()\n\n print('>>> Sampling user info into ' + str(self.userDbFile) + ' ...')\n\n userTableList = common.getSqlTableList(self.userDbFile, self.userDbCurs)\n busersDic = common.getBusersInfo()\n userList = busersDic['USER/GROUP']\n\n # Insert 'sampleTime', 'DATE', 'TIME' and 'SECONDS' into key list.\n origKeyList = list(busersDic.keys())\n keyList = self.addKeyDateInfo(origKeyList)\n\n for i in range(len(userList)):\n user = userList[i]\n userTableName = 'user_' + str(user)\n print(' Sampling for user \"' + str(user) + '\" ...')\n\n # Get the user value infos.\n valueList = []\n valueList = self.addValueDateInfo(valueList)\n for key in origKeyList:\n keyValue = busersDic[key][i]\n valueList.append(keyValue)\n\n # Generate sql table.\n if userTableName not in userTableList:\n keyString = common.genSqlTableKeyString(keyList)\n common.createSqlTable(self.userDbFile, self.userDbConn, userTableName, keyString)\n\n # Insert sql table value.\n valueString = common.genSqlTableValueString(valueList)\n common.insertIntoSqlTable(self.userDbFile, self.userDbConn, userTableName, valueString)\n\n self.userDbCurs.close()\n self.userDbConn.close()\n\n def sampling(self):\n while True:\n if self.jobSampling:\n p = Process(target=self.sampleJobInfo)\n p.start()\n if self.queueSampling:\n p = Process(target=self.sampleQueueInfo)\n p.start()\n if self.hostSampling:\n p = Process(target=self.sampleHostInfo)\n p.start()\n if self.loadSampling:\n p = Process(target=self.sampleLoadInfo)\n p.start()\n if self.userSampling:\n p = Process(target=self.sampleUserInfo)\n p.start()\n\n if self.interval == 0:\n break\n elif self.interval > 0:\n time.sleep(self.interval)\n\n#################\n# Main Function #\n#################\ndef main():\n (job, queue, host, load, user, interval) = readArgs()\n mySampling = sampling(job, queue, host, load, user, interval)\n mySampling.sampling()\n\nif __name__ == '__main__':\n main()\n","sub_path":"monitor/bin/bsample.py","file_name":"bsample.py","file_ext":"py","file_size_in_byte":13758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"32082733","text":"dictionary_global = {}\n\n\nclass DictionaryPractice1:\n\n @classmethod\n def fill_dictionary(cls):\n number_of_elements = int(cls.read_length_of_dictionary())\n global dictionary_global\n for i in range(1, number_of_elements + 1):\n key_to_insert = cls.read_and_verify_is_key_exists()\n value_to_insert = cls.read_and_verify_is_value_exists()\n dictionary_global.update({key_to_insert: value_to_insert})\n\n @classmethod\n def read_length_of_dictionary(cls):\n while True:\n try:\n return int(input('How many elements you will insert into dictionary?: '))\n except ValueError:\n print(\"Is not valid number, please try again.\")\n pass\n\n @classmethod\n def read_and_verify_is_key_exists(cls):\n while True:\n key_to_verify = input(\"Insert Key: \")\n if cls.is_key_inserted_exists(key_to_verify):\n print(\"The key [{}] already exists, try again\".format(key_to_verify))\n else:\n return key_to_verify\n\n @classmethod\n def read_and_verify_is_value_exists(cls):\n while True:\n value_to_verify = input(\"Insert Value: \")\n if cls.is_value_inserted_exists(value_to_verify):\n print(\"The value [{}] already exists, try again\".format(value_to_verify))\n else:\n return value_to_verify\n\n @classmethod\n def print_the_dictionary_keys(cls):\n print(dictionary_global.keys())\n\n @classmethod\n def print_the_dictionary_values(cls):\n print(dictionary_global.values())\n\n @classmethod\n def print_the_dictionary(cls):\n print(dictionary_global)\n\n @classmethod\n def is_key_inserted_exists(cls, key):\n return key in dictionary_global.keys()\n\n @classmethod\n def is_value_inserted_exists(cls, key):\n return key in dictionary_global.values()\n\n @classmethod\n def run_practice_one(cls):\n print(\"PRACTICE 1\")\n cls.fill_dictionary()\n print(\"=> Function to print the dictionary keys\")\n cls.print_the_dictionary_keys()\n print(\"=> Function to print the dictionary values\")\n cls.print_the_dictionary_values()\n print(\"=> Function to print the dictionary\")\n cls.print_the_dictionary()\n print(\"=> Function to define is a key inserted by the user, exists on the dictionary.\")\n cls.read_and_verify_is_key_exists()\n print(\"=> Function to define is a value inserted by the user, exists on the dictionary.\")\n cls.read_and_verify_is_value_exists()\n\n\nscript = DictionaryPractice1\nscript.run_practice_one()\n","sub_path":"OmarHuanca/python/session3/DictionaryPractice1.py","file_name":"DictionaryPractice1.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"397149485","text":"\nimport os\nfrom queue import Queue, Empty\nfrom . import config\nfrom .core import flatten, reverse_dict, get_dependencies, has_tasks, _execute_task\nfrom .order import order\nfrom .callbacks import unpack_callbacks, local_callbacks\nfrom .utils_test import add, inc # noqa: F401\nif os.name == \"nt\":\n # Python 3 windows Queue.get doesn't handle interrupts properly. To\n # workaround this we poll at a sufficiently large interval that it\n # shouldn't affect performance, but small enough that users trying to kill\n # an application shouldn't care.\n def queue_get(q):\n while True:\n try:\n return q.get(block=True, timeout=0.1)\n except Empty:\n pass\nelse:\n def queue_get(q):\n return q.get()\nDEBUG = False\ndef start_state_from_dask(dsk, cache=None, sortkey=None):\n \n if sortkey is None:\n sortkey = order(dsk).get\n if cache is None:\n cache = config.get(\"cache\", None)\n if cache is None:\n cache = dict()\n data_keys = set()\n for k, v in dsk.items():\n if not has_tasks(dsk, v):\n cache[k] = v\n data_keys.add(k)\n dsk2 = dsk.copy()\n dsk2.update(cache)\n dependencies = {k: get_dependencies(dsk2, k) for k in dsk}\n waiting = {k: v.copy() for k, v in dependencies.items() if k not in data_keys}\n dependents = reverse_dict(dependencies)\n for a in cache:\n for b in dependents.get(a, ()):\n waiting[b].remove(a)\n waiting_data = dict((k, v.copy()) for k, v in dependents.items() if v)\n ready_set = set([k for k, v in waiting.items() if not v])\n ready = sorted(ready_set, key=sortkey, reverse=True)\n waiting = dict((k, v) for k, v in waiting.items() if v)\n state = {\n \"dependencies\": dependencies,\n \"dependents\": dependents,\n \"waiting\": waiting,\n \"waiting_data\": waiting_data,\n \"cache\": cache,\n \"ready\": ready,\n \"running\": set(),\n \"finished\": set(),\n \"released\": set(),\n }\n return state\n\ndef execute_task(key, task_info, dumps, loads, get_id, pack_exception):\n \n try:\n task, data = loads(task_info)\n result = _execute_task(task, data)\n id = get_id()\n result = dumps((result, id))\n failed = False\n except BaseException as e:\n result = pack_exception(e, dumps)\n failed = True\n return key, result, failed\ndef release_data(key, state, delete=True):\n \n if key in state[\"waiting_data\"]:\n assert not state[\"waiting_data\"][key]\n del state[\"waiting_data\"][key]\n state[\"released\"].add(key)\n if delete:\n del state[\"cache\"][key]\ndef finish_task(\n dsk, key, state, results, sortkey, delete=True, release_data=release_data\n):\n \n for dep in sorted(state[\"dependents\"][key], key=sortkey, reverse=True):\n s = state[\"waiting\"][dep]\n s.remove(key)\n if not s:\n del state[\"waiting\"][dep]\n state[\"ready\"].append(dep)\n for dep in state[\"dependencies\"][key]:\n if dep in state[\"waiting_data\"]:\n s = state[\"waiting_data\"][dep]\n s.remove(key)\n if not s and dep not in results:\n if DEBUG:\n from chest.core import nbytes\n print(\n \"Key: %s\\tDep: %s\\t NBytes: %.2f\\t Release\"\n % (key, dep, sum(map(nbytes, state[\"cache\"].values()) / 1e6))\n )\n release_data(dep, state, delete=delete)\n elif delete and dep not in results:\n release_data(dep, state, delete=delete)\n state[\"finished\"].add(key)\n state[\"running\"].remove(key)\n return state\ndef nested_get(ind, coll):\n \n if isinstance(ind, list):\n return tuple([nested_get(i, coll) for i in ind])\n else:\n return coll[ind]\ndef default_get_id():\n \n return None\ndef default_pack_exception(e, dumps):\n raise\ndef reraise(exc, tb=None):\n if exc.__traceback__ is not tb:\n raise exc.with_traceback(tb)\n raise exc\ndef identity(x):\n \n return x\n\ndef get_async(\n apply_async,\n num_workers,\n dsk,\n result,\n cache=None,\n get_id=default_get_id,\n rerun_exceptions_locally=None,\n pack_exception=default_pack_exception,\n raise_exception=reraise,\n callbacks=None,\n dumps=identity,\n loads=identity,\n **kwargs\n):\n \n queue = Queue()\n if isinstance(result, list):\n result_flat = set(flatten(result))\n else:\n result_flat = set([result])\n results = set(result_flat)\n dsk = dict(dsk)\n with local_callbacks(callbacks) as callbacks:\n _, _, pretask_cbs, posttask_cbs, _ = unpack_callbacks(callbacks)\n started_cbs = []\n succeeded = False\n # if start_state_from_dask fails, we will have something\n # to pass to the final block.\n state = {}\n try:\n for cb in callbacks:\n if cb[0]:\n cb[0](dsk)\n started_cbs.append(cb)\n keyorder = order(dsk)\n state = start_state_from_dask(dsk, cache=cache, sortkey=keyorder.get)\n for _, start_state, _, _, _ in callbacks:\n if start_state:\n start_state(dsk, state)\n if rerun_exceptions_locally is None:\n rerun_exceptions_locally = config.get(\"rerun_exceptions_locally\", False)\n if state[\"waiting\"] and not state[\"ready\"]:\n raise ValueError(\"Found no accessible jobs in dask\")\n def fire_task():\n \n # Choose a good task to compute\n key = state[\"ready\"].pop()\n state[\"running\"].add(key)\n for f in pretask_cbs:\n f(key, dsk, state)\n # Prep data to send\n data = dict(\n (dep, state[\"cache\"][dep]) for dep in get_dependencies(dsk, key)\n )\n # Submit\n apply_async(\n execute_task,\n args=(\n key,\n dumps((dsk[key], data)),\n dumps,\n loads,\n get_id,\n pack_exception,\n ),\n callback=queue.put,\n )\n # Seed initial tasks into the thread pool\n while state[\"ready\"] and len(state[\"running\"]) < num_workers:\n fire_task()\n # Main loop, wait on tasks to finish, insert new ones\n while state[\"waiting\"] or state[\"ready\"] or state[\"running\"]:\n key, res_info, failed = queue_get(queue)\n if failed:\n exc, tb = loads(res_info)\n if rerun_exceptions_locally:\n data = dict(\n (dep, state[\"cache\"][dep])\n for dep in get_dependencies(dsk, key)\n )\n task = dsk[key]\n _execute_task(task, data) # Re-execute locally\n else:\n raise_exception(exc, tb)\n res, worker_id = loads(res_info)\n state[\"cache\"][key] = res\n finish_task(dsk, key, state, results, keyorder.get)\n for f in posttask_cbs:\n f(key, res, dsk, state, worker_id)\n while state[\"ready\"] and len(state[\"running\"]) < num_workers:\n fire_task()\n succeeded = True\n finally:\n for _, _, _, _, finish in started_cbs:\n if finish:\n finish(dsk, state, not succeeded)\n return nested_get(result, state[\"cache\"])\n\ndef apply_sync(func, args=(), kwds={}, callback=None):\n \n res = func(*args, **kwds)\n if callback is not None:\n callback(res)\ndef get_sync(dsk, keys, **kwargs):\n \n kwargs.pop(\"num_workers\", None) # if num_workers present, remove it\n return get_async(apply_sync, 1, dsk, keys, **kwargs)\ndef sortkey(item):\n \n return (type(item).__name__, item)\n","sub_path":"dask/local.py_no_comments.py","file_name":"local.py_no_comments.py","file_ext":"py","file_size_in_byte":8173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"397005295","text":"#!/usr/bin/env python\n#-*-coding:utf-8-*-\nimport re\nfrom gpjspider.utils.constants import *\nimport requests\nfrom scrapy.selector import Selector\nimport datetime\n\ndef color(value):\n \"\"\"\n 【出售广东二手黑色大众帕萨特2001款 帕萨特 旅行车 1.8T 自动(进口) 买费用都值啦】_14年行驶17.00万公里-网上车市\n 【出售湖北二手黑2012款 30 FSI CVT 豪华型】_2年行驶4.00万公里-网上车市\n 【出售北京二手深灰色2012款 E200L 1.8T CGI优雅型】_3年行驶7.90万公里-网上车市\n \"\"\"\n if u'色' in value:\n ret = re.findall(u'二手(\\S+色)', value)\n if ret:\n return ret[0]\n else:\n return ''\n else:\n ret = re.findall(u'二手(\\S{1,2})\\d*', value)\n if ret and u'其他' not in ret[0]:\n if re.search('\\d+', ret[0]):\n return ret[0][:-1]\n else:\n return ret[0]\n else:\n return ''\n\ndef brand_or_model(value):\n if u'车' in value:\n return ''\n if u'二手' in value:\n if re.search(u'二手(.*)', value):\n return re.search(u'二手(.*)', value).group(1)\n return ''\n return ''\n\ndef source_type(value):\n if u'个人' in value:\n return SOURCE_TYPE_GONGPINGJIA\n elif u'4' in value:\n return SOURCE_TYPE_SELLER\n elif u'商家' in value:\n return SOURCE_TYPE_ODEALER\n\ndef model_url(value):\n \"\"\" /zhengzhou/chevrolet/73/ \"\"\"\n if value.count('/') == 4:\n return value\n else:\n return ''\n\ndef phone(value):\n if u'http://seller.cheshi.com' in ''.join(value):\n return None\n elif u'/0200/goto.php?url' in ''.join(value):\n value = 'http://2sc.cheshi.com' + value[0]\n page = Selector(text=requests.get(value).text)\n value = page.xpath('//span[@class=\"telephone\"]/img/@src').extract()\n if value:\n value = ['http://cc.ganji.com' + value[0]]\n else:\n value = page.xpath('//b[@class=\"teltype\"]/text()').extract()\n return value and value[0] or None\n\ndef volume(value):\n value.reverse()\n a = re.compile(r'(\\d\\.\\d)').findall(' '.join(value))\n return a and a[-1] or '0'\n\ndef year(value):\n # import ipdb;ipdb.set_trace()\n if u'0年' in value:\n value = [str(datetime.datetime.now().year)]\n return value[0]\n\ndef control(value):\n if u'无极变速' in value or u'双离合变速' in value:\n value = u'自动'\n return value\n\ndef mile(value):\n if '0.00' in value:\n value = u'0.01万公里'\n return value\n","sub_path":"gpjspider/processors/cheshi.py","file_name":"cheshi.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"105513337","text":"# Prime Number - The number which is divisible by 1 and itself\nimport math\nfor num in range(10, 20):\n if num > 1:\n for j in range(2, num):\n if num % j == 0:\n break\n else:\n print(num)\n\nnum = 11\nwhile num % 2 == 0:\n print(\"not a prime\")\n break\nelse:\n print(\"Prime\")\n\nnum = 20\nfor i in range(num):\n if math.gcd(num, i) == 1:\n print(i)","sub_path":"Programs/Prime Number.py","file_name":"Prime Number.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"197574759","text":"# -*- coding: utf-8 -*-\n##Euler's Totient function, phi(n) [sometimes called the phi function], is used to\n##determine the number of positive numbers less than or equal to n which are\n##relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than\n##nine and relatively prime to nine, phi(9)=6.\n##The number 1 is considered to be relatively prime to every positive number, so\n##phi(1)=1.\n##\n##Interestingly, phi(87109)=79180, and it can be seen that 87109 is a permutation\n##of 79180.\n##\n##Find the value of n, 1 n 107, for which φ(n) is a permutation of n and the\n##ratio n/phi(n) produces a minimum.\n\nfrom math import sqrt\n\nimport time\nstart = time.time()\na = open(\"primes.txt\")\n\nprimes = []\n\nfor line in a:\n primes.append(int(line))\n\n\n\ndef phi2(p1, p2):\n return int(p1*p2*(1-1./p1)*(1-1./p2))\n\ndef phi(n):\n res = n\n a = factor(n)\n if a == []:\n return 1\n for f in a:\n res = res*(1-1./f)\n return int(res)\n\n# function taken from p62\ndef make_num_dict(n):\n num_str = str(n)\n num_dict = {}\n for num in num_str:\n try:\n num_dict[num] += 1\n except:\n num_dict[num] = 1\n return num_dict\n\nbest = 1000\nwinner = None\n\ndef compare(s1, s2):\n str_list = []\n str_list2 = []\n for letter in str(s1):\n str_list.append(letter)\n for letter in str(s2):\n str_list2.append(letter)\n str_list.sort()\n str_list2.sort()\n if str_list == str_list2:\n return True\n else:\n return False\n\np_mult_list = []\n\nfor i in range(0, len(primes)):\n a = primes[i]\n if a > 10**7:\n break\n for j in range(i, len(primes)):\n b = primes[j]\n c = a*b\n if c > 10**7:\n break\n p = phi2(a, b)\n if 1.*c/p < best:\n if compare(c, p):\n best = 1.*c/p\n winner = c\n\nprint(winner)\n\n\n##if make_num_dict(87109) == make_num_dict(phi(87109)):\n## print('ok')\n\nfinish = time.time()\nprint(finish - start)\n \n \n\n","sub_path":"code/Python/old/Euler/p70_v3.py","file_name":"p70_v3.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"488293098","text":"\"\"\" Test the class_student. \"\"\"\nimport unittest, datetime\n\nfrom student import Person, Student, UG, Grad, Gradesbook\n\nclass Test_Person(unittest.TestCase):\n\n def setUp(self):\n self.mili, self.bob = Person('Mili Chad'), Person('Bob Paradis')\n self.zoe, self.anabel = Person('Zoe Lalonde'), Person('Potter')\n\n self.mili.birthday = datetime.date(1969, 5, 22)\n self.bob.birthday = datetime.date(1968, 7, 9)\n return super().setUp()\n\n def tearDown(self):\n del self.mili\n del self.bob\n del self.zoe\n del self.anabel\n return super().tearDown()\n\n def test_init_Person(self):\n self.assertEqual(self.mili.name, 'Mili Chad')\n self.assertEqual(self.anabel.name, 'Potter')\n self.assertEqual(self.zoe.last_name, 'Lalonde')\n self.assertEqual(self.mili.birthday, datetime.date(1969, 5, 22))\n self.assertIsNone(self.anabel.birthday)\n with self.assertRaises(TypeError):\n dan = Person(124)\n dan.__birthday = 1969\n\n def test_getter_Person(self):\n self.assertEqual(self.mili.name, 'Mili Chad')\n self.assertEqual(self.anabel.last_name, 'Potter')\n self.assertEqual(self.zoe.last_name, 'Lalonde')\n self.assertEqual(self.bob.get_age(), (datetime.date.today() - datetime.date(1968, 7, 9)).days)\n with self.assertRaises(ValueError):\n self.anabel.get_age()\n\n def test_lt_Person(self):\n self.assertLess(self.mili, self.bob)\n self.assertLess(self.zoe, self.anabel)\n\n def test_sorting(self):\n roster: list = [self.zoe, self.mili, self.bob, self.anabel]\n roster.sort()\n self.assertEqual(roster, [self.mili, self.zoe, self.bob, self.anabel])\n\nclass Test_Student(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print(\"setupclass Student\")\n\n @classmethod\n def tearDownClass(cls):\n # Resetting a class variable to its initial value\n Student.nextid_num = 0\n\n def setUp(self):\n self.student1 = Student('Mark Guttag')\n self.student2 = Student('Billy Bob Beaver')\n self.student4 = Person('Billy Stephenson') # Not a student`\n self.student3 = Student('Billy Bob Beaver')\n self.student5 = Grad('Buzz Aldrin')\n self.student6 = UG('Billy Beaver', 1984)\n return super().setUp()\n\n def tearDown(self):\n del self.student1\n del self.student2\n del self.student3\n del self.student4\n del self.student5\n del self.student6\n return super().tearDown()\n\n def test_init_Student(self):\n # Student 4 is not a Student so does not increment the id_num\n\n self.assertEqual(self.student1.name, 'Mark Guttag')\n self.assertEqual(self.student1.id_num, 0)\n self.assertEqual(self.student2.name, 'Billy Bob Beaver')\n self.assertEqual(self.student2.id_num, 1)\n self.assertEqual(self.student3.name, 'Billy Bob Beaver')\n self.assertEqual(self.student3.id_num, 2)\n self.assertEqual(self.student5.name, 'Buzz Aldrin')\n self.assertEqual(self.student5.__str__(), 'Buzz Aldrin')\n self.assertEqual(self.student5.id_num, 3)\n self.assertEqual(self.student6.name, 'Billy Beaver')\n self.assertEqual(self.student6.id_num, 4)\n self.assertEqual(self.student6.year, 1984)\n\n # Assigning a bday that raises error b/c not datetime\n with self.assertRaises(TypeError):\n self.student6.birthday = 'a1984'\n\n self.assertTrue(self.student6.isstudent())\n\n def test_lt_Student(self):\n # Uses the id_num to determine relative order\n self.assertLess(self.student1, self.student2)\n self.assertLess(self.student2, self.student3)\n self.assertGreater(self.student3, self.student2)\n\nclass Test_Gradesbook(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print(\"setupclass testGrades\")\n\n @classmethod\n def tearDownClass(cls):\n # Resetting a class variable to its initial value\n Student.nextid_num = 0\n\n def setUp(self):\n self.undergrad1 = UG('Jane Doe', 2014)\n self.undergrad2 = UG('John Doe', 2015)\n self.undergrad3 = UG('David Henry', 2003)\n self.grad1, self.grad2 = Grad('Billy Buckner'), Grad('Bucky F. Dent')\n\n self.six_hundred = Gradesbook()\n self.six_hundred.add_student(self.undergrad1)\n self.six_hundred.add_student(self.undergrad2)\n self.six_hundred.add_student(self.grad1)\n self.six_hundred.add_student(self.grad2)\n return super().setUp()\n\n def tearDown(self):\n del self.undergrad1\n del self.undergrad2\n del self.undergrad3\n del self.grad1\n del self.grad2\n del self.six_hundred\n return super().tearDown()\n\n def test_Loading_Students(self):\n self.assertIn(self.undergrad1, self.six_hundred.students)\n self.assertIn(self.undergrad2, self.six_hundred.students)\n self.assertIn(self.grad1, self.six_hundred.students)\n self.assertIn(self.grad2, self.six_hundred.students)\n\n def test_duplicate_Students(self):\n with self.assertRaises(ValueError):\n self.six_hundred.add_student(self.undergrad1)\n\n def test_Loading_grades(self):\n # Go through the list of students (using the copy) and place 75 in the grade\n for student in self.six_hundred.students:\n self.six_hundred.add_grade(student, 75)\n\n # Then add grades to a few students\n self.six_hundred.add_grade(self.grad1, 25)\n self.six_hundred.add_grade(self.grad2, 100)\n self.six_hundred.add_student(self.undergrad3)\n self.six_hundred.add_grade(self.grad2, 90)\n\n self.assertEqual(self.six_hundred.get_grades(self.grad1), [75, 25])\n self.assertEqual(self.six_hundred.get_grades(self.grad2), [75, 100, 90])\n\n def test_adding_grade_non_student(self):\n # Try to add grade to a non-existent student\n self.grad5 = Person('Bob')\n with self.assertRaises(AttributeError):\n self.six_hundred.add_grade(self.grad5, 25)\n\n def test_get_grades_non_student(self):\n # Try to add grade to a non-existent student\n self.grad5 = Person('Bob')\n with self.assertRaises(AttributeError):\n self.six_hundred.get_grades(self.grad5)\n\n def test_average_grade(self):\n # Go through the list of students (using the copy) and place 75 in the grade\n for student in self.six_hundred.students:\n self.six_hundred.add_grade(student, 75)\n self.six_hundred.add_grade(self.grad1, 25)\n\n self.assertEqual(self.six_hundred.calculate_average(self.grad1), 50)\n self.assertEqual(self.six_hundred.calculate_average(self.grad2), 75)\n\n def test_average_grade_no_student(self):\n self.undergrad4 = UG('Enigma', 2003)\n self.six_hundred.add_student(self.undergrad4)\n self.assertEqual(self.six_hundred.calculate_average(self.undergrad4), -99.)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Classes/project_student/tests/test_student.py","file_name":"test_student.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"77754075","text":"from ..autoclass import AutoDatabank\nfrom ..actionfunc import timedelta, parse, somedays\nfrom ..actionfunc import swtime, checktime, two_check_time\nfrom ..actionfunc import t365, t180, tnow\nfrom .. import autoclass\nimport json\n\nmodulepath = autoclass.__file__[:-12] + 'setini/' + 'eightxx'\n\ndglc = AutoDatabank(zhanghao=2, tmall_global=False, purchase_Behaviour='dp')\ndglc.yybp_order = 0\ndglc.ppld_order = 0\n\n\ndef reloaddglc():\n global dglc\n with open(modulepath, 'r') as f:\n izh, tg, pb, o1, o2, o3, o4, o5 = json.load(f)['valuex']\n dglc = autoclass.AutoDatabank(izh, tg, pb)\n dglc.yybp_order = o1\n dglc.ppld_order = o2\n dglc.ppzq_order = o3\n dglc.mxdp_order = o4\n dglc.zszw_order = o5\n print('重载成功...')\n#★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★#\n\n\ndef diaoyong_tracking(t2bef, t2end, diaoyongname, shengchengname, zhuanhuarenqun, Xmodel=1):\n reloaddglc()\n xname = 'xX' if Xmodel == 3 else ''\n leixinname = ''\n\n def cp3():\n nonlocal leixinname\n dglc.cp()\n if zhuanhuarenqun == 'jindian':\n leixinname = '进店'\n dglc.zdy('%s【辅】进店ZDY' % shengchengname)\n elif zhuanhuarenqun == 'shoucang':\n leixinname = '收藏'\n dglc.dp(2, t2bef, t2end)\n elif zhuanhuarenqun == 'jiagou':\n leixinname = '加购'\n dglc.dp(3, t2bef, t2end)\n elif zhuanhuarenqun == 'yushou':\n leixinname = '预售'\n dglc.dp(4, t2bef, t2end)\n elif zhuanhuarenqun == 'baoguang':\n leixinname = '曝光'\n dglc.zszw([1, 99], t2bef, t2end, action=1)\n\n cp3()\n dglc.zdy('%sv4】旗店深A' % diaoyongname, Xmodel)\n dglc.sp('%s-%s深A%s%s' % (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv5】旗店浅A' % diaoyongname, Xmodel)\n dglc.sp('%s-%s浅A%s%s' %\n (diaoyongname, shengchengname, xname, leixinname)) # A\n\n cp3()\n dglc.zdy('%sv11】超I浅I' % diaoyongname, Xmodel)\n dglc.zdy('%sv10】超I深I' % diaoyongname, 2)\n dglc.sp('%s-%s超级用户I%s%s' %\n (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv13】非超I深I' % diaoyongname, Xmodel)\n dglc.sp('%s-%s深度I%s%s' % (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv14】非超I浅I' % diaoyongname, Xmodel)\n dglc.sp('%s-%s浅度I%s%s' % (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv8】非店之I' % diaoyongname, Xmodel)\n dglc.sp('%s-%s非店I%s%s' %\n (diaoyongname, shengchengname, xname, leixinname)) # I\n\n cp3()\n dglc.zdy('%sv17】旗店PL活跃' % diaoyongname, Xmodel)\n dglc.sp('%s-%s旗店活跃PL%s%s' %\n (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv18】旗店PL非活' % diaoyongname, Xmodel)\n dglc.sp('%s-%s旗店非活PL%s%s' %\n (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv20】非店PL活跃' % diaoyongname, Xmodel)\n dglc.sp('%s-%s非店活跃PL%s%s' %\n (diaoyongname, shengchengname, xname, leixinname))\n\n cp3()\n dglc.zdy('%sv21】非店PL非活' % diaoyongname, Xmodel)\n dglc.sp('%s-%s非店非活PL%s%s' %\n (diaoyongname, shengchengname, xname, leixinname)) # PL\n","sub_path":"personal/pc1030.py","file_name":"pc1030.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"438336573","text":"# This file is part of the Adblock Plus web scripts,\n# Copyright (C) 2006-present eyeo GmbH\n#\n# Adblock Plus is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 3 as\n# published by the Free Software Foundation.\n#\n# Adblock Plus is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Adblock Plus. If not, see .\n\nimport re\nimport email.header\nimport email.utils\nimport urllib\nimport time\nimport json\nfrom datetime import date\nfrom jinja2.utils import Markup\nfrom urlparse import urlparse\n\n\ndef formattime(value):\n try:\n return time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(int(value)))\n except Exception as e:\n return 'unknown'\n\n\ndef formatrelativetime(value, baseTime):\n try:\n value = float(value)\n params = {'title': formattime(baseTime + value), 'number': value, 'prefix': 'in ', 'suffix': '', 'unit': 'second(s)'}\n if params['number'] < 0:\n params['prefix'] = ''\n params['suffix'] = ' ago'\n params['number'] = -params['number']\n if params['number'] >= 180:\n params['unit'] = 'minutes'\n params['number'] /= 60\n if params['number'] >= 180:\n params['unit'] = 'hours'\n params['number'] /= 60\n if params['number'] >= 72:\n params['unit'] = 'days'\n params['number'] /= 24\n if params['number'] >= 21:\n params['unit'] = 'weeks'\n params['number'] /= 7\n return Markup('%(prefix)s%(number)i %(unit)s%(suffix)s' % params)\n except Exception:\n return 'unknown'\n\n\ndef formaturl(url, title=None):\n if not url:\n return ''\n\n if title is None:\n title = url\n parsed = urlparse(url)\n if parsed.scheme == 'http' or parsed.scheme == 'https':\n url = Markup.escape(url)\n title = Markup.escape(title)\n title = unicode(title).replace('*', '*').replace(u'\\u2026', u'\\u2026')\n return Markup('%(title)s' % {'url': url, 'title': title})\n else:\n return url\n\n\ndef formatnewlines(value):\n value = Markup.escape(value)\n value = unicode(value).replace('\\n', '
')\n return Markup(value)\n\n\ndef formatfiltercount(value):\n try:\n value = int(value)\n if value > 0:\n return 'yes, %i filter(s)' % value\n else:\n return 'none'\n except Exception:\n return 'unknown'\n\n\ndef formatBugLinks(value):\n def addLink(match):\n linkApp = match.group(1)\n if linkApp != None:\n linkApp = linkApp.lower()\n linkType = match.group(2).lower()\n linkNum = int(match.group(3))\n if linkType == 'topic':\n link = 'https://adblockplus.org/forum/viewtopic.php?t=%i' % linkNum\n elif linkApp == None and linkType == 'issue':\n link = 'https://issues.adblockplus.org/ticket/%i' % linkNum\n elif linkApp == 'webkit':\n link = 'https://bugs.webkit.org/show_bug.cgi?id=%i' % linkNum\n elif linkApp != None:\n link = 'http://code.google.com/p/chromium/issues/detail?id=%i' % linkNum\n else:\n link = 'https://bugzilla.mozilla.org/show_bug.cgi?id=%i' % linkNum\n return '%s' % (link, match.group(0))\n\n regexp = re.compile(r'(https?://\\S+?)([.,:;!?\"\\']?(?:\\s|$))', re.I | re.U)\n regexp2 = re.compile(r'(?:\\b(WebKit|Chrome|Chromium)\\s+)?\\b(bug|issue|topic)\\s+(\\d+)', re.I | re.U)\n value = unicode(Markup.escape(value))\n value = re.sub(regexp, r'\\1\\2', value)\n value = re.sub(regexp2, addLink, value)\n return Markup(value)\n\n\ndef urlencode(value):\n return urllib.quote(value.encode('utf-8'), '')\n\n\ndef subscriptionSort(value, prioritizeRecommended=True):\n value = value[:] # create a copy of the list\n if prioritizeRecommended:\n value.sort(\n lambda a, b:\n cmp(a.type, b.type) or\n cmp(a.deprecated, b.deprecated) or\n cmp(b.catchall, a.catchall) or\n cmp(b.recommendation != None, a.recommendation != None) or\n cmp(a.name.lower(), b.name.lower()),\n )\n else:\n value.sort(\n lambda a, b:\n cmp(a.type, b.type) or\n cmp(a.deprecated, b.deprecated) or\n cmp(a.name.lower(), b.name.lower()),\n )\n return value\n\n\ndef formatmime(text):\n # See http://bugs.python.org/issue5871 (not really fixed), Header() will\n # happily accept non-printable characters including newlines. Make sure to\n # remove them.\n text = re.sub(r'[\\x00-\\x1F]', '', text)\n return email.header.Header(text).encode()\n\n\ndef ljust(value, width=80):\n return unicode(value).ljust(width)\n\n\ndef rjust(value, width=80):\n return unicode(value).rjust(width)\n\n\ndef ltruncate(value, length=255, end='...'):\n value = unicode(value)\n if len(value) <= length:\n return value\n return end + value[len(value) - length:len(value)]\n\n\ndef formatweekday(value):\n return time.strftime('%a', (0, 0, 0, 0, 0, 0, value, 0, 0))\n\n\ndef formatbytes(value):\n if value == 0:\n return '0'\n\n value = float(value)\n unit = 'Bytes'\n if value > 1024:\n value /= 1024\n unit = 'KB'\n if value > 1024:\n value /= 1024\n unit = 'MB'\n if value > 1024:\n value /= 1024\n unit = 'GB'\n return '%.2f %s' % (value, unit)\n\n\ndef toJSON(value, **args):\n return re.sub(r'', r'<\\/script>', json.dumps(value, **args))\n\n\nfilters = {\n 'formattime': formattime,\n 'timerelative': formatrelativetime,\n 'url': formaturl,\n 'keepnewlines': formatnewlines,\n 'filtercount': formatfiltercount,\n 'buglinks': formatBugLinks,\n 'urlencode': urlencode,\n 'subscriptionSort': subscriptionSort,\n 'mime': formatmime,\n 'emailaddr': email.utils.formataddr,\n 'ljust': ljust,\n 'rjust': rjust,\n 'ltruncate': ltruncate,\n 'weekday': formatweekday,\n 'bytes': formatbytes,\n 'json': toJSON,\n}\n","sub_path":"sitescripts/templateFilters.py","file_name":"templateFilters.py","file_ext":"py","file_size_in_byte":6494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651851451","text":"import json\nimport logging\n\nimport sys\nfrom optparse import OptionParser\n\nimport requests\n\n\nclass ZabbixAPIException(Exception):\n pass\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass MonitorDescription:\n zabbix_servers = {\n \"JMX\": \"java.zabbix.dooioo.com\",\n \"SERVER\": \"server.zabbix.dooioo.com\"\n }\n\n default_template_names = {\n \"JMX\": [\"Template JMX Generic\"],\n \"SERVER\": [\"Template OS Linux\"]\n }\n\n default_host_groups = {\n \"JMX\": ['JMX'],\n \"SERVER\": ['Linux']\n }\n\n def __init__(self, ip, interface_port=10811, monitor_type='JMX'\n , host_group_names=None, monitor_template_names=None\n , http_test_resource='/api/it/ping', http_test_port=9600):\n self.ip = ip\n self.interface_port = interface_port\n self.monitor_type = monitor_type if monitor_type else 'JMX'\n if self.monitor_type == 'JMX':\n self.interface_type = 4\n else:\n self.interface_type = 1\n self.host_group_names = host_group_names if host_group_names else self.default_host_groups[monitor_type]\n if monitor_template_names:\n self.monitor_template_names = self.default_template_names[\"JMX\"]\n self.monitor_template_names.extend(monitor_template_names)\n else:\n self.monitor_template_names = self.default_template_names['JMX']\n self.http_test_resource = http_test_resource\n self.http_test_port = http_test_port\n self.build_zabbix_server()\n self.host_group_ids = []\n self.template_ids = []\n\n def build_zabbix_server(self):\n try:\n self.api_url = 'http://{0}/api_jsonrpc.php' \\\n .format(self.zabbix_servers[self.monitor_type])\n except Exception as e:\n raise ZabbixAPIException(\"检查你输入的监控类型是否正确,目前支持:JMX, SERVER两种类型\")\n\n\nclass ZabbixClient:\n \"\"\"\n Generic Zabbix API Client\n - login\n - get auth\n \"\"\"\n global_header = {\n 'Content-Type': 'application/json-rpc',\n 'User-Agent': 'python-zabbix-client',\n 'Cache-Control': 'no-cache'\n }\n\n def __init__(self, monitor_description, user_name=None, password=None, timeout=None):\n self.user_name = user_name if user_name else '110863'\n self.password = password if password else '123456'\n self.session = requests.session()\n self.session.headers.update(self.global_header)\n self.auth = ''\n self.id = 0\n self.timeout = timeout if timeout else 20\n self.zabbix_api_url = monitor_description.api_url\n self.monitor_description = monitor_description\n\n def login(self):\n \"\"\"\n login with given user_name and password, if None, use default user\n :param user_name:\n :param password:\n :return: result,auth key\n \"\"\"\n self.auth = self.user.login(user=self.user_name, password=self.password)\n\n def api_version(self):\n return self.apiinfo.version()\n\n def get_exiting_host_group_ids(self):\n \"\"\"\n get exiting host group name to avoid host group not existing error\n :param host_group_names:\n :return:\n \"\"\"\n host_group = self.hostgroup.get(\n filter={\n 'name': self.monitor_description.host_group_names\n })\n logger.info(str(host_group) + \"is found\")\n if len(host_group) == 0:\n raise ZabbixAPIException(self.host_group_names + \" is not existing\")\n host_group_ids = []\n for item in host_group:\n host_group_ids.append({\"groupid\": item['groupid']})\n self.monitor_description.host_group_ids = host_group_ids\n return host_group_ids\n\n def get_existing_templates(self):\n \"\"\"\n get exiting monitor templates\n :param monitor_template:\n :return:\n \"\"\"\n templates = self.template.get(filter={\n \"host\": self.monitor_description.monitor_template_names\n })\n for item in templates:\n self.monitor_description.template_ids.append({\"templateid\": item['templateid']})\n return templates\n\n def create_host(self):\n \"\"\"\n create new host\n \"\"\"\n created_host = self.host.create(\n host=self.monitor_description.ip,\n interfaces=[{\n \"type\": self.monitor_description.interface_type,\n \"main\": 1,\n \"useip\": 1,\n \"ip\": self.monitor_description.ip,\n \"dns\": \"\",\n \"port\": self.monitor_description.interface_port\n }],\n groups=self.monitor_description.host_group_ids\n )\n new_host_id = created_host['hostids'][0]\n return new_host_id\n\n def link_template_to_host(self, host_id):\n \"\"\"\n\n :param host_id:\n :return:\n \"\"\"\n if host_id:\n template = self.template.massadd(\n templates=self.monitor_description.template_ids,\n hosts=[{\"hostid\": host_id}]\n )\n return template\n\n def create_monitor(self):\n self.login()\n self.get_exiting_host_group_ids()\n self.get_existing_templates()\n host_id = self.create_host()\n self.link_template_to_host(host_id)\n return host_id\n\n def httptest_create(self, host_id, monitor_description):\n \"\"\"\n create http test like ping /api/it/ping\n :param host_id:\n :param name:\n :param ip:\n :param port:\n :param http_test_resource:\n :return:\n \"\"\"\n\n if host_id:\n httptest_request = {\n 'retries': '1',\n 'status': '0',\n 'agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) '\n 'AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8',\n 'steps': [\n {\n 'no': '1',\n 'status_codes': '200',\n 'posts': '',\n 'variables': '',\n 'timeout': '15',\n 'url': 'http://' + self.monitory_description.ip + ':' + str(\n self.monitory_description.http_test_port) + monitor_description.http_test_resource,\n 'required': '',\n 'name': self.monitory_description.ip + '_' + str(self.monitory_description.http_test_port)\n }\n ],\n 'authentication': '0',\n 'macros': '',\n 'hostid': host_id,\n 'variables': '',\n 'delay': '30',\n 'http_password': '',\n 'name': self.monitory_description.ip + '_' + str(self.monitory_description.http_test_port)\n }\n\n http_test = self.httptest.create(httptest_request)\n return http_test\n\n def do_request(self, method, params=None):\n request_json = {\n 'jsonrpc': '2.0',\n 'method': method,\n 'params': params or {},\n 'id': self.id,\n }\n\n if method != 'apiinfo.version' and self.auth:\n request_json['auth'] = self.auth\n\n logger.info(\"sending: %s\", json.dumps(request_json, indent=4, separators=(',', ':')))\n response = self.session.post(\n self.monitor_description.api_url,\n data=json.dumps(request_json),\n timeout=self.timeout\n )\n logger.info(\"Response Code : %s\", str(response.status_code))\n\n response.raise_for_status()\n\n if not len(response.text):\n raise ZabbixAPIException(\"没有返回值\")\n try:\n response_json = json.loads(response.text)\n except ValueError:\n raise ZabbixAPIException(\"不能解析JSON %s\" % response.text)\n\n logger.info(\"sending: %s\", json.dumps(request_json, indent=4, separators=(',', ':')))\n\n self.id += 1\n\n if 'error' in response_json:\n if 'data' not in response_json['error']:\n response_json['error']['data'] = 'No Data'\n msg = \"Error {code}: {message},{data}\".format(\n code=response_json['error']['code'],\n message=response_json['error']['message'],\n data=response_json['error']['data']\n )\n raise ZabbixAPIException(msg, response_json['error']['code'])\n return response_json\n\n def __getattr__(self, item):\n \"\"\"\n auto create Zabbix API Client\n :param item:\n :return:\n \"\"\"\n return ZabbixAPIObjectClass(item, self)\n\n\nclass ZabbixAPIObjectClass(object):\n \"\"\"\n Zabbix API Object for API client\n \"\"\"\n\n def __init__(self, name, parent):\n self.name = name\n self.parent = parent\n\n def __getattr__(self, item):\n \"\"\"\n dynamic create a method (get,create,update,delete, or others)\n :param item:\n :return:\n \"\"\"\n\n def fn(*args, **kwargs):\n if args and kwargs:\n raise TypeError('只能输入一种参数,value或者 key=value形式')\n\n return self.parent.do_request('{0}.{1}'.format(self.name, item),\n args or kwargs)['result']\n\n return fn\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-t\", '--monitor_template_names',\n help=\"输入模版名称,默认为JMX:Template JMX Generic,SERVER:Template OS Linux\")\n parser.add_option(\"-i\", '--ip', help=\"输入HOST的IP地址\")\n parser.add_option(\"-m\", '--monitor_type', help=\"监控类型:JMX or SERVER\", default='JMX')\n parser.add_option(\"-a\", '--interface_port', help=\"监控代理端口:agent interface port\", default=10811)\n parser.add_option(\"-g\", '--host_group_names', help=\"host group names\")\n parser.add_option(\"-p\", '--http_test_resource', help=\"服务检查URL,默认为/api/it/ping\", default='/api/it/ping')\n parser.add_option(\"-P\", '--http_test_port', help=\"服务检查端口,默认为9600端口\", default=9600)\n\n (options, args) = parser.parse_args()\n print(options)\n monitor_description = MonitorDescription(ip=options.ip\n , interface_port=options.interface_port\n , monitor_type=options.monitor_type\n , host_group_names=options.host_group_names\n , monitor_template_names=options.monitor_template_names\n , http_test_resource=options.http_test_resource\n , http_test_port=options.http_test_port)\n\n client = ZabbixClient(monitor_description)\n client.create_monitor()\n","sub_path":"python_client/zabbix/zabbixclient.py","file_name":"zabbixclient.py","file_ext":"py","file_size_in_byte":10917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"319170332","text":"\n# this renders the home page which is start.html\nfrom app.allImports import *\n@app.route(\"/post/\", methods = [\"GET\"])\ndef post(pid):\n post = Post.get(Post.pid == pid)\n return render_template(\"post.html\",\n post = post,\n cfg = cfg) # Do not worry about cfg, but you need\n # to pass that as an argument everytime\n # with render_template\n","sub_path":"app/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"545675123","text":"from django.test import TestCase\n\n# Create your tests here.\nfrom .models import Source, Comments, Program\n\nclass sourceTest(TestCase):\n\tdef setUp(self):\n\t\ta0 = Source.objects.create(title='App1', description='test description a0', instructions='do the app please', display_order=1, lesson_typ='programming assignment')\n\t\t#program0 = Program.objects.create(code='PUBLIC STATIC MAIN VOID', source = a0)\n\t\tc0 = Comments.objects.create(comment='PUBLIC STATIC MAIN VOID IS THE MANTRA OF LEARNING PROGRAMMING WITHOUT BEING TAUGHT OBJECTS', display_order=0, program=program0)\n\t\tc1 = Comments.objects.create(comment='THIS IS THE SECOND COMMENT', display_order=1, program=program0)\n\n\t\ta1 = Source.objects.create(title='App2', description='test models for app', instructions='i really dont know', display_order=2, lesson_typ='programming assignment')\n\t\tprogram1 = Program.objects.create(code='int main(void) {return 0;}', source=a1)\n\t\tc2 = Comments.objects.create(comment='this is crazy talk', display_order=2, program=program1)\n\t\tc3 = Comments.objects.create(comment='ANYONE READ THESE?', display_order=3, program=program1)\n\n\t#def test_get_source(self):\n\t\t#source = Course.objects.get(title='App1')\n","sub_path":"lessons_site/sourceDropApp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"109998227","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'PokemonGo.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'search.views.index', name='newIndex'),\n url(r'^pokemon$', 'search.views.index', name='index'),\n #url(r'^random$', 'search.views.random', name='random'),\n url(r'^searchGET$', 'search.views.searchget', name='searchGET'),\n url(r'^searchPOST$', 'search.views.searchpost', name='searchPOST'),\n #url(r'^search/(\\d+)$', 'search.views.search2', name='search2'),\t\t#unnamed grouping\n #url(r'^search/(?P\\d+)', 'search.views.search2', name='search2'), #named grouping\n #url(r'^pokedex$', 'search.views.newIndex', name='newIndex'),\n url(r'^searchREDIRECT/(?P[\\*\\w\\-]+)/$', 'search.views.searchredirect', name='searchredirect'),\n url(r'^searchLISTJS$', 'search.views.searchlistjs', name='searchLISTJS'),\n url(r'^edit/(\\d+)', 'search.views.edit', name=\"edit\"),\n)\n","sub_path":"PokemonGo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"421887833","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pandas import Series, DataFrame\nfrom json_util import load_json\nimport datetime as dt\nimport sys\n\nDATE_FORMAT = '%Y-%m-%d %H:%M:%S'\n\nfield = sys.argv[1]\n\ndef select_time(dict):\n return dict['time']\n\ndef load_data(path):\n json_data = list(load_json(path))\n for d in json_data:\n d['time'] = dt.datetime.strptime(d['time'], DATE_FORMAT)\n\n return DataFrame(data=json_data, index=map(select_time, json_data))\n\n\ngps_data = load_data('c1_gps.txt')\nlogger_data = load_data('c1_data.txt')\n\ntry:\n p = logger_data[field].plot()\nexcept:\n p = gps_data[field].plot()\n\nif len(sys.argv) == 3:\n y_label = sys.argv[2]\nelse:\n y_label = sys.argv[1]\n\np.set_ylabel(y_label)\np.set_xlabel(\"Time\")\n\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"439902668","text":"# you can also test to see if two numbers are not equal \r\n\r\n#answer = 17\r\n\r\n#if answer != 42:\r\n\t#print(\"That is not the correct answer. Please try again!\")\r\n\r\n#age_0 = 22\r\n#age_1 = 18 \r\n\r\n#and_0 >= 21 and age_1 >= 21\r\n\r\n\r\n# check whether a value is in a list \r\n\r\nrequested_toppings = ['mushrooms', 'onions', 'pinapple']\r\nanswer = 'mushrooms' in requested_toppings \r\nprint(answer)\r\n\r\n# also can use in an if loop to check if it isnt a part of a list \r\n\r\nbanned_users = ['paul', 'HW', 'Nikki']\r\nuser = 'other'\r\n\r\nif user not in banned_users:\r\n\tprint(user.title() + \", you can post a response if you wish\")\r\n\t\r\n\r\n# Boolean value is either True or False, just like the value of a \r\n# conditional expressional expression after it has been evaluated\r\n\r\n# Boolean values provide an efficient way to track the state of a program\r\n# or a particular condition that is important in programming \r\n\r\n\r\n\t\r\n","sub_path":"magic_number.py","file_name":"magic_number.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619512621","text":"from django.contrib import admin\n\nfrom .models import Article, List, Subscribers\n\n\n# Register your models here.\n\nclass ArticleAdminInline(admin.TabularInline):\n model = Article\n\nclass SubListAdminInline(admin.TabularInline):\n model = List\n\nclass ListAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('name', 'link', 'parent')\n }),\n ('Advanced options', {\n 'classes': ('collapse',),\n 'fields': ()\n }),\n )\n inlines = [ArticleAdminInline, SubListAdminInline]\n search_fields = ['name']\n list_display = ('id', 'name', 'link', 'parent')\n\nadmin.site.register(List, ListAdmin)\n\nclass ArticleAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('name', 'text', 'pub_date', 'author', 'list', )\n }),\n ('Advanced options', {\n 'classes': ('collapse',),\n 'fields': ()\n }),\n )\n\n search_fields = ['name']\n list_display = ('id', 'name', 'text', 'pub_date', 'author', 'list', )\n list_filter = ['pub_date']\n\nadmin.site.register(Article, ArticleAdmin)\n\nclass SubscribersAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('follower', 'following',)\n }),\n ('Advanced options', {\n 'classes': ('collapse',),\n 'fields': ()\n }),\n )\n search_fields = ['follower', 'following',]\n list_display = ('id', 'follower', 'following',)\n\nadmin.site.register(Subscribers, SubscribersAdmin)\n","sub_path":"doc/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"332448633","text":"class Solution:\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n l = 0\n r = len(nums)-1\n if(len(nums)==0):\n return [-1, -1]\n elif(len(nums)==1):\n if(nums[0]==target):\n return [0, 0]\n else:\n return [-1, -1]\n\n mid = (l+r)//2\n while(l<=r):\n mid = (l+r)//2\n if(nums[mid]==target):\n l = mid\n r= mid\n while(l>=0 and nums[l]==target):\n l=l-1\n while(rtarget):\n r = mid-1\n elif(nums[mid]\"\"\")\n\n html.append(\"\"\"\n \"\"\")\n\n html.append(\"\"\"\n \"\"\")\n\n html.append(\"\"\"\n \"\"\")\n for t in cst.tous_les_types:\n if len(t) > 0:\n html.append(\"\"\"\n \"\"\".format(t.title()))\n\n html.append(\"\"\"\n \"\"\")\n\n for t1 in cst.tous_les_types:\n html.append(\"\"\"\n \"\"\")\n if len(t1) > 0:\n html.append(\"\"\"\n \"\"\".format(t1.title()))\n else:\n html.append(\"\"\"\n \"\"\")\n\n for t2 in cst.tous_les_types:\n if len(t2) > 0:\n if len(t1) > 0:\n nombre = len(cst.combinaisons_types[(t1, t2)])\n else:\n nombre = len(cst.combinaisons_types[(t2, \"\")])\n if nombre > 0:\n couleur = calcule_couleur_dégradé(\n nombre, cst.nombre_pokemon_maxi)\n # url = Universal Remote Location\n if len(t1) > 0:\n url = \"/categories?type1={}&type2={}\".format(t1, t2)\n else:\n url = \"/type/{}\".format(t2)\n html.append(\n \"\"\"\n \"\"\".format(url, couleur, nombre))\n else:\n html.append(\"\"\"\n \"\"\")\n\n html.append(\"\"\"\n \"\"\")\n\n html.append(\"\"\"\n
{}
{}Empty{}
\"\"\")\n html.append(\"\"\"\n \"\"\")\n","sub_path":"app/matrice.py","file_name":"matrice.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"151751941","text":"import pipeline\nimport workers\n\n\ndef hello_pipeline():\n pipeline.Pipeline([\n pipeline.Task(HelloWorldProducer, 1),\n pipeline.Task(PrintConsumer, 1)\n ]).execute()\n\n\nclass HelloWorldProducer(workers.Producer):\n def process(self):\n self.out_queue.put('{}: Hello World'.format(self.name))\n\n\nclass PrintConsumer(workers.Consumer):\n def process(self, item):\n print(\"{}: '{}'\".format(self.name, str(item)))\n\n\nif __name__ == '__main__':\n hello_pipeline()\n","sub_path":"hello_pipeline.py","file_name":"hello_pipeline.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"363242474","text":"import torch\nimport numpy as np\nfrom datasets import test_data\nfrom torchvision import transforms\ndevice=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nto_pil_image = transforms.ToPILImage()\ndef print_img(image):\n image = image.cpu().squeeze(0)\n img = to_pil_image(image[:])\n img.convert('RGB')\n img.show()\nimg,target,label = test_data[0]\nprint_img(img)\n\nprint(label)\nt_con_mask = torch.ByteTensor(target.size()).to(device)\nt_con_mask.zero_()\nt_con_mask[:, :, 4] = 1\n\nt_confidence = target[t_con_mask].cpu().numpy()\nt_sorted_idx = np.argsort(-t_confidence)\nt_sorted_con = np.sort(-t_confidence)\n\nt_i = 0\nt_rst = []\nwhile True:\n if -t_sorted_con[t_i] < 1:\n break\n t_row = t_sorted_idx[t_i] // 28\n t_line = t_sorted_idx[t_i] % 28\n t_r = target[ t_row, t_line, 5]\n t_rst.append(t_r.item())\n t_i += 1\nprint(t_rst)","sub_path":"fixerror.py","file_name":"fixerror.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"122274889","text":"\"\"\"The class used to manipulate lists of Atoms\n\"\"\"\nimport numpy as np\n# from copy import copy\nfrom copy import deepcopy\n\nfrom fromage.utils.atom import Atom\nimport fromage.io.edit_file as ef\n\ndef try_ismol(to_test):\n \"\"\" Raise exception if the argument is not a Mol object\"\"\"\n if not isinstance(to_test, Mol):\n raise TypeError(\"Cannot cast \" +\n type(to_test).__name__ + \" to Mol object\")\n\ndefault_thresh = {'dis' : 1.8,\n 'cov' : 0.2,\n 'vdw' : -0.3}\n\nclass Mol(object):\n \"\"\"\n Object representing a list of atoms.\n\n This class can be used to reflect any number of molecules, point charges or\n unit cells. Although Mol shares many methods with list, it deliberately does\n not inherit it in order to avoid nonsensical operations such as Mol1 > Mol2\n\n Attributes\n ----------\n atoms : list of Atom objects\n Member atoms of Mol\n vectors : 3 x 3 numpy array\n Lattice vectors of the unit cell\n bonding : string 'dist, 'cov' or 'vdw'\n The method for detecting bonding in this molecule.\n 'dis' : distance between atoms < threshold\n 'cov' : distance - (cov radius of atom a + of atom b) < threshold\n 'vdw' : distance - (vwd radius of atom a + of atom b) < threshold\n thresh : float, optional\n Threshold for the detection. If None, use defaults\n\n \"\"\"\n\n\n\n def __init__(self, in_atoms=[], vectors=np.zeros((3, 3)), bonding = 'dis', thresh = 1.8):\n # In case the user feeds a lone atom:\n if isinstance(in_atoms, Atom):\n in_atoms = [in_atoms]\n self.atoms = in_atoms\n self.vectors = vectors\n self.bonding = bonding\n self.thresh = thresh\n def __repr__(self):\n out_str = \"\"\n for atom in self.atoms:\n out_str += atom.__str__() + \"\\n\"\n return out_str\n\n def __str__(self):\n return self.__repr__()\n\n def set_bonding(self, bonding='dis', thresh=None):\n \"\"\"\n Set the type of bonding detection used in this Mol\n\n Parameters\n ----------\n bonding : string 'dis', 'cov' or 'vdw'\n The method for detecting bonding in this molecule.\n 'dis' : distance between atoms < threshold\n 'cov' : distance - (cov radius of atom a + of atom b) < threshold\n 'vdw' : distance - (vwd radius of atom a + of atom b) < threshold\n thresh : float, optional\n Threshold for the detection. If None, use defaults:\n 'dis' -> 1.8\n 'cov' -> 0.2\n 'vdw' -> -0.3\n\n \"\"\"\n if bonding not in default_thresh:\n raise TypeError(\"Unrecognised bonding type: \"+ bonding)\n self.bonding = bonding\n if thresh:\n self.thresh = thresh\n else:\n self.thresh = default_thresh[bonding]\n return\n\n def set_bonding_str(self, in_str):\n \"\"\"\n Set the type of bonding and threshold with one string\n\n The string is of the type \"cov0.2\" or \"dis1.7\" etc. But giving just the\n threshold or just the bonding gives the default for the ommitted part.\n The order of the bonding and threshold does not matter, so \"vdw2.2\" is\n the same as \"2.2vdw\"\n\n Parameters\n ----------\n in_str : str\n The string which determines the bonding where the threshold and the\n distance are set to default if none are supplied\n\n \"\"\"\n bondings = default_thresh.keys()\n bonding = ''\n thresh_str = ''\n # check if bonding has been specified\n for i_bonding in bondings:\n if i_bonding in in_str:\n bonding = i_bonding\n # if there is bonding, try to find threshold\n if bonding:\n stripped = in_str.replace(bonding,'')\n # if there is still a thresh in this string\n if stripped:\n thresh_str = stripped\n # if only the thresh is specified\n elif in_str:\n thresh_str = in_str\n # if both present\n if bonding and thresh_str:\n self.set_bonding(bonding=bonding,thresh=float(thresh_str))\n # if only bonding\n if bonding and not thresh_str:\n self.set_bonding(bonding=bonding)\n # if only thresh\n if thresh_str and not bonding:\n self.set_bonding(thresh=float(thresh_str))\n if not thresh_str and not bonding:\n self.set_bonding()\n return\n\n def bonded(self, atom_a, atom_b):\n \"\"\"\n Check if atom_a is bonded to atom_b given the bonding settings\n\n Parameters\n ----------\n atom_a, atom_b : Atom objects\n The atoms to be compared\n Returns\n -------\n bonded_bool : bool\n True if the atoms are bonded and False if not\n \"\"\"\n bonded_bool = atom_a.dist(atom_b, ref=self.bonding) <= self.thresh\n return bonded_bool\n\n def per_bonded(self, atom_a, atom_b):\n \"\"\"\n Check if atom_a is bonded to atom_b given lattice conditions\n\n Parameters\n ----------\n atom_a, atom_b : Atom objects\n The atoms to be compared\n Returns\n -------\n bonded_bool : bool\n True if the atoms are bonded and False if not\n \"\"\"\n bonded_bool = atom_a.per_dist(atom_b, self.vectors, ref=self.bonding) <= self.thresh\n return bonded_bool\n\n # list-y behaviour\n def append(self, element):\n self.atoms.append(element)\n\n def extend(self, other_mol):\n self.atoms.extend(other_mol.atoms)\n\n def insert(self, i, element):\n self.atoms.insert(i, element)\n\n def remove(self, element):\n self.atoms.remove(element)\n\n def index(self, element):\n return self.atoms.index(element)\n\n def pop(self, i=-1):\n return self.atoms.pop(i)\n\n def clear(self):\n self.atoms.clear()\n\n def count(self, element):\n return self.atoms.count()\n\n def __add__(self, other_mol):\n try_ismol(other_mol)\n return Mol(deepcopy(self).atoms + other_mol.atoms, vectors = self.vectors, bonding = self.bonding, thresh = self.thresh)\n\n def __len__(self):\n return len(self.atoms)\n\n def __eq__(self, other):\n return self.atoms == other.atoms\n\n def __getitem__(self, index):\n return self.atoms[index]\n\n def __setitem__(self, index, value):\n self.atoms[index] = value\n return\n\n def __contains__(self, elem):\n return self.atoms.__contains__(elem)\n\n def copy(self):\n return deepcopy(self)\n\n def write_xyz(self, name):\n \"\"\"Write an xyz file of the Mol\"\"\"\n ef.write_xyz(name, self.atoms)\n\n def empty_mol(self):\n \"\"\"Return an empty mol with the same properties\"\"\"\n new_mol = deepcopy(self)\n new_mol.atoms = []\n return new_mol\n\n def select(self, labels):\n \"\"\"\n Return a molecule out of the current Mol.\n\n The function returns a new Mol of selected atoms atoms. The selection is\n done by measuring by how much adjacent vdw spheres overlap. The returned\n Mol's attributes are new objects obtained via a deep copy.\n\n Parameters\n ----------\n label : int or list of ints\n The number of the atoms from which the molecules are generated.\n\n Returns\n -------\n selected : Mol object\n The selected molecule\n \"\"\"\n\n # Make sure that labels is a list\n if isinstance(labels, int):\n labels = [labels]\n\n # Check for duplicate labels\n if len(labels) > len(set(labels)):\n raise TypeError(\"Some labels are repeated\")\n\n selected = self.copy()\n selected.atoms = deepcopy([self[i] for i in labels])\n remaining = self.copy()\n for atom in selected:\n if atom in remaining:\n remaining.remove(atom)\n\n old_atoms = selected.copy()\n\n # While there are atoms to add\n cont = True\n while cont:\n cont = False\n new_atoms = Mol([])\n for old in old_atoms:\n tmp_remaining = remaining.copy()\n for rem in remaining:\n if self.bonded(old,rem):\n new_atoms.append(rem)\n selected.append(rem)\n tmp_remaining.remove(rem)\n cont = True # An atom was added so continue loop\n remaining = tmp_remaining\n old_atoms = new_atoms\n return selected\n\n def per_select(self, labels, old_pos=False):\n \"\"\"\n Select a molecule out of a Mol in a periodic system.\n\n Parameters\n ----------\n labels : int or list of ints\n The number of the atoms from which the molecules are generated\n old_pos : bool\n Option to print the selected molecule at its original coordinates\n\n Returns\n -------\n selected_img : Mol object\n The atoms belonging to the molecule which is selected with certain\n atoms translated so that the molecule is fully connected without\n periodic boundaries\n selected_old : Mol object (optional)\n The atoms belonging to the molecule which is selected before\n translations\n\n \"\"\"\n\n # Make sure that labels is a list\n if isinstance(labels, int):\n labels = [labels]\n\n # Check for duplicate labels\n if len(labels) > len(set(labels)):\n raise TypeError(\"Some labels are repeated\")\n\n # Mol of selected atoms from the unit cell\n selected_old = self.copy()\n selected_old.atoms = [self[i] for i in labels]\n\n # Mol of selected atoms where the periodic image\n # atoms are translated back to form a molecule\n selected_img = selected_old.copy()\n\n remaining = self.copy()\n for atom in selected_old:\n if atom in remaining:\n remaining.remove(atom)\n\n old_atoms = selected_old.copy()\n\n # While there are atoms to add\n cont = True\n while cont == True:\n cont = False\n new_atoms = Mol([])\n for old in old_atoms:\n tmp_remaining = remaining.copy()\n for rem in remaining:\n # contains the distance from the point or image and the\n # coordinates of the point or image\n dist, per_img = old.per_dist(rem, self.vectors, ref=self.bonding, new_pos=True)\n # if the atom is close enough to be part of the molecule\n if dist <= self.thresh:\n new_atoms.append(per_img)\n selected_old.append(rem)\n selected_img.append(per_img)\n tmp_remaining.remove(rem)\n cont = True # An atom was added so continue loop\n remaining = tmp_remaining\n old_atoms = new_atoms\n\n\n if old_pos:\n return selected_img, selected_old\n else:\n return selected_img\n\n def segregate(self):\n \"\"\"Separate current Mol in a list of Mols of different molecules\"\"\"\n molecules = [] # list of molecules\n remaining = self.copy()\n\n while len(remaining) > 0:\n molecule = remaining.select(0)\n molecules.append(molecule)\n for atom in molecule:\n remaining.remove(atom)\n return molecules\n\n def complete_mol(self, labels):\n \"\"\"\n Take a cell and complete certain molecules\n\n The objective is to end up with a unit cell where the molecules of interest\n are complete. The rest of the atoms of the cell must remain intact. Note that\n the input atoms are transformed and are the same as are present in the\n output.\n\n Parameters\n ----------\n labels : int or list of ints\n The number of the atoms from which the molecules are generated\n Returns\n -------\n new_mol : Mol object\n The now complete molecule\n new_cell : Mol object\n The cell with the completed molecule\n \"\"\"\n new_mol, scattered_mol = self.per_select(labels, old_pos=True)\n new_cell_atoms = deepcopy(\n [a for a in self.atoms if a not in scattered_mol])\n new_cell = self.copy()\n new_cell.atoms = new_cell_atoms\n\n for atom in new_mol:\n new_cell.append(atom.copy())\n return new_mol, new_cell\n\n def complete_cell(self):\n \"\"\"\n Return a cell where atoms have been translated to complete all molecules of\n the cell\n\n Returns\n -------\n out_cell : Mol object\n The new untruncated cell\n full_mol_l : list of Mol objects\n Each molecule in the untruncated cell\n\n \"\"\"\n full_mol_l = []\n remaining = self.copy()\n\n while len(remaining) != 0:\n full_mol, cell = remaining.complete_mol(0)\n full_mol_l.append(full_mol)\n remaining = cell\n for atom in full_mol:\n if atom in remaining:\n remaining.remove(atom)\n\n # Convinently, remaining is now an empty Mol\n out_cell = remaining\n for mol in full_mol_l:\n out_cell.extend(mol)\n return out_cell, full_mol_l\n\n def centroid(self):\n \"\"\"Return np array of the centroid\"\"\"\n N = len(self.atoms)\n centro = np.array([0.0, 0.0, 0.0])\n for atom in self.atoms:\n centro[0] += atom.x\n centro[1] += atom.y\n centro[2] += atom.z\n centro = centro / N\n return centro\n\n def center_mol(self):\n \"\"\"Translate molecules to center\"\"\"\n cen = self.centroid()\n for atom in self.atoms:\n atom.v_translate(-cen)\n return\n\n def translate(self, vector):\n \"\"\"\n Translate Mol by a vector\n\n Parameters\n ----------\n vector : 3 x 1 numpy array\n Translation vector\n\n \"\"\"\n for atom in self.atoms:\n atom.v_translate(vector)\n return\n\n def supercell(self, trans):\n \"\"\"\n Return a supercell of I x J x K\n\n Parameters\n ----------\n trans : array-like of length 3\n Multiplications of the primitive cell\n Returns\n -------\n supercell : Mol object\n New supercell with adjusted lattice vectors\n\n \"\"\"\n # make the input into a np array\n trans = np.array(trans)\n\n new_cell = self.empty_mol()\n for a_mult in range(trans[0]):\n for b_mult in range(trans[1]):\n for c_mult in range(trans[2]):\n vector = a_mult * \\\n self.vectors[0] + b_mult * \\\n self.vectors[1] + c_mult * self.vectors[2]\n new_atoms = Mol([i.v_translated(vector)\n for i in self.atoms])\n new_cell += new_atoms\n out_vec = (self.vectors.T * trans.transpose()).T\n new_cell.vectors = out_vec\n return new_cell\n\n def centered_supercell(self, trans, from_origin=False):\n \"\"\"\n Make a bigger supercell out of an input cell.\n\n The cell is multiplied positively and negatively through each lattice\n vector so that the supercluster ends up being\n (1+2*trans[0])*(1+2*trans[1])*(1+2*trans[2]) times larger. For example if the\n input is 1,1,1 for a cubic unit cell, the output will be the original unit\n cell surrounded by 26 other unit cells forming a total 3x3x3 cube.\n\n Alternatively, the multiplication can be centered around the origin, a corner of the\n unit cell, instead of the centre. In that case the supercluster ends up being\n only (2*trans[0])*(2*trans[1])*(2*trans[2])\n\n Parameters\n ----------\n trans : numpy array of length 3\n Multiplications of the primitive cell\n from_origin : bool\n Determines the kind of multiplication. True is corner of the cell as\n the center, False is middle of the cell.\n\n Returns\n -------\n mega_cell : Mol object\n The resulting supercell\n\n \"\"\"\n trans_series = [0, 0, 0]\n for i, tra in enumerate(trans):\n if from_origin:\n trans_series[i] = list(range(-tra, tra))\n else:\n trans_series[i] = list(range(-tra, tra + 1))\n trans_series = np.array(trans_series)\n\n new_cell = self.empty_mol()\n for a_mult in trans_series[0]:\n for b_mult in trans_series[1]:\n for c_mult in trans_series[2]:\n vector = a_mult * \\\n self.vectors[0] + b_mult * \\\n self.vectors[1] + c_mult * self.vectors[2]\n new_atoms = Mol([i.v_translated(vector)\n for i in self.atoms])\n new_cell += new_atoms\n out_vec = (self.vectors.T * trans.transpose()).T\n new_cell.vectors = out_vec\n return new_cell\n\n def trans_from_rad(self, clust_rad):\n \"\"\"\n Generate the translations necessary to encapsulate a sphere of given rad\n\n Parameters\n ----------\n clust_rad : float\n Radius defining a sphere\n\n Returns\n -------\n trans_count : 3 x 1 numpy array\n The translations required for the unit cell to contain the sphere\n\n \"\"\"\n\n # determine how many unit cells we need\n vectors = deepcopy(self.vectors)\n\n # vectors normal to faces\n a_perp = np.cross(vectors[1], vectors[2])\n b_perp = np.cross(vectors[2], vectors[0])\n c_perp = np.cross(vectors[0], vectors[1])\n\n # the three normalised unit vectors\n perp = np.array([a_perp / np.linalg.norm(a_perp), b_perp /\n np.linalg.norm(b_perp), c_perp / np.linalg.norm(c_perp)])\n\n trans_count = np.array([1, 1, 1])\n\n # distances from faces\n distances = np.array([0.0, 0.0, 0.0])\n\n new_vectors = deepcopy(vectors)\n\n for comp in range(3):\n while True:\n trans_count[comp] += 1\n distances[comp] = np.dot(new_vectors[comp], perp[comp])\n new_vectors[comp] = trans_count[comp] * vectors[comp]\n if distances[comp] > clust_rad:\n break\n trans_count -= np.array([1, 1, 1])\n return trans_count\n\n def make_cluster(self, clust_rad, mode = 'exc', central_mol = None):\n \"\"\"\n Generate a cluster of molecules from a primitive cell\n\n This first makes a supercell of the correct size which will contain with\n one additional buffer shell. Then the sphere is generated from this new\n supercell by connectivity.\n\n A central molecule can also be supplied which will turn the spheres\n defining the clusters into the union of spheres stemming from each atom\n of the central molecule.\n\n Parameters\n ----------\n clust_rad : float\n Radius defining a sphere. All molecules with atoms in the sphere are\n to be grabbed\n mode : str\n Switches between inclusive and exclusive selecting. Inclusive,\n 'inc', selects all molecules which have atoms within the radius.\n Exclusive, 'exc', selects all molecules fully in the radius.\n Default: false\n central_mol : Mol\n If this is supplied, the central molecule will act as a kernel for\n the cluster which will end up being of the appropriate shape.\n Returns\n -------\n cluster : Mol object\n Spherical cluster of molecules from their crystal positions\n\n \"\"\"\n # if there is a central mol, account for nearest neighbour molecules\n # bleeding out of the original radius\n if central_mol:\n central_rad = 0\n for atom in central_mol:\n dis = atom.v_dist([0,0,0])\n if dis < central_rad:\n central_rad = dis\n trans = self.trans_from_rad(clust_rad + central_rad)\n # get the translations necessary to enclose the required mols\n else:\n trans = self.trans_from_rad(clust_rad)\n # if the cluster is inclusive, then extra mols might be required from\n # an additional layer of the supercell\n if mode == 'inc':\n trans += np.array([1,1,1]) # one buffer cell layer\n supercell = self.centered_supercell(trans, from_origin=True)\n\n seed_atoms = Mol([])\n\n # get seedatoms in the shape of the central mol if pertinent\n if central_mol:\n for atom_i in supercell:\n for atom_j in central_mol:\n if atom_i.dist(atom_j) < clust_rad:\n seed_atoms.append(atom_i)\n break\n # get spherical seedatoms\n else:\n for atom in supercell:\n if atom.v_dist([0, 0, 0]) < clust_rad:\n seed_atoms.append(atom)\n\n \n max_mol_len = 0\n if mode == 'exc':\n while len(seed_atoms) > 0:\n mol = seed_atoms.select(0)\n if len(mol) > max_mol_len:\n max_mol_len = len(mol)\n clust_atoms = Mol([])\n if len(mol) == max_mol_len:\n clust_atoms += mol\n for atom in mol:\n seed_atoms.remove(atom)\n if mode == 'inc':\n clust_atoms = Mol([])\n max_mol_len = len(supercell.select(supercell.index(seed_atoms[0])))\n\n while len(seed_atoms) > 0:\n mol_tmp = seed_atoms.select(0) # The part of the mol detected in seed_atoms\n if len(mol_tmp) < max_mol_len:\n # The whole mol, which could potentially include even more seed_atoms\n mol = supercell.select(supercell.index(seed_atoms[0]))\n else:\n mol = mol_tmp\n clust_atoms += mol\n for atom in mol_tmp:\n seed_atoms.remove(atom)\n for atom in mol:\n supercell.remove(atom)\n # remove all atoms of the mol which are part of seed_atoms\n try:\n seed_atoms.remove(atom)\n except ValueError:\n pass\n\n return clust_atoms\n\n def remove_duplicates(self, thresh=0.001):\n \"\"\"Remove the duplicate atoms\"\"\"\n purged_mol = Mol([self.atoms[0]])\n for atom_a in self[1:]:\n unique = True\n for atom_b in purged_mol:\n if atom_a.very_close(atom_b, thresh=thresh):\n unique = False\n break\n if unique:\n purged_mol.append(atom_a)\n self.atoms = purged_mol\n return\n\n def dir_to_frac_pos(self):\n \"\"\"Move all atoms to fractional coordinates\"\"\"\n\n out_mol = self.copy()\n # transpose to get the transformation matrix\n M = np.transpose(self.vectors)\n # inverse transformation matrix\n U = np.linalg.inv(M)\n\n for atom in out_mol:\n # change of basis transformation\n dir_pos = atom.get_pos()\n frac_pos = np.dot(U, dir_pos)\n for i, coord in enumerate(frac_pos):\n # if the coordinate is out of range\n if coord < 0 or coord > 1:\n # translate it to the range [0,1]\n frac_pos[i] = coord % 1\n atom.set_pos(frac_pos)\n return out_mol\n\n def frac_to_dir_pos(self):\n \"\"\"Move all atoms to direct coordinates\"\"\"\n out_mol = self.copy()\n for atom in out_mol:\n new_pos = np.matmul(self.vectors.T, atom.get_pos())\n atom.set_pos(new_pos)\n\n return out_mol\n\n def confined(self):\n \"\"\"Move all atoms to fit inside the primitive cell\"\"\"\n frac_mol = self.dir_to_frac_pos()\n out_mol = frac_mol.frac_to_dir_pos()\n\n return out_mol\n\n def centered_mols(self, labels, return_trans = False):\n \"\"\"\n Return the molecules translated at the origin with a corresponding cell\n\n Parameters\n ----------\n labels : int or list of ints\n The labels of the atoms to select\n print_centro : bool\n Print the translation vector which was detected as -centroid\n Returns\n -------\n mol : Mol object\n The selected molecules with their centroid at the origin\n mod_cell : Mol object\n The new confined cell corresponding to the now translated molecules\n\n \"\"\"\n mol, mod_cell = self.complete_mol(labels)\n centro = mol.centroid()\n mol.translate(-centro)\n mod_cell.translate(-centro)\n mod_cell = mod_cell.confined()\n\n if return_trans:\n return mol, mod_cell, -centro\n else:\n return mol, mod_cell\n\n\n def es_pot(self, position):\n \"\"\"\n Return the electorstatic potential generated by this Mol\n\n Parameters\n ----------\n position : 3x1 np array\n The point at which the potential should be evaluated\n Returns\n -------\n tot_pot : float\n The total potential\n\n \"\"\"\n tot_pot = 0\n for atom in self:\n tot_pot += atom.es_pot(position)\n return tot_pot\n\n def change_charges(self, charges):\n \"\"\"\n Change all of the charges of the constituent atoms at once\n\n Parameters\n ----------\n charges : array-like of floats\n Contains all of the new charges. IMPORTANT: they need to be in the\n order corresponding to self.atoms\n\n \"\"\"\n for i, atom in enumerate(self.atoms):\n atom.q = charges[i]\n return\n\n def charges(self):\n \"\"\"Return an array of charges\"\"\"\n l_char = []\n for atom in self.atoms:\n l_char.append(atom.q)\n arr_char = np.array(l_char)\n return arr_char\n\n def raw_assign_charges(self, charges):\n \"\"\"Assign the charges from an array-like to the atoms\"\"\"\n for char,at in zip(charges,self.atoms):\n at.q=char\n return\n\n def populate(self, reference_mol):\n \"\"\"\n Assign charges to the Mol by comparing to the connectivity of a\n reference\n\n Parameters\n ----------\n reference_mol : Mol object\n Charged molecule or cell\n\n \"\"\"\n # This is a naughty in-function import to prevent a circular dependency.\n # The reason is that assign_charges functions are grouped up with the\n # executable script which needs to read_file and in turn use mol.py\n # Some careful refactoring should fix this\n import fromage.scripts.assign_charges as ac\n ac.assign_charges(reference_mol, self)\n pass\n","sub_path":"fromage/utils/mol.py","file_name":"mol.py","file_ext":"py","file_size_in_byte":27343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"442725203","text":"from django.urls import path\n\nfrom .views import (CardCreateView, DeckListView, CardListView, DeckUpdateView,\n CardUpdateView, CardDeleteView, DeckDeleteView, deck_create)\n\napp_name = 'words'\n\nurlpatterns = [\n path('decks/add/', deck_create, name='deck_add'),\n path('decks/', DeckListView.as_view(), name='deck_list'),\n path('/cards/', CardListView.as_view(), name='card_list'),\n path('/cards/add/', CardCreateView.as_view(), name='card_add'),\n path('decks//', DeckUpdateView.as_view(), name='deck_update'),\n path('cards//', CardUpdateView.as_view(), name='card_update'),\n path('cards//delete/', CardDeleteView.as_view(), name='card_delete'),\n path('decks//delete/', DeckDeleteView.as_view(), name='deck_delete'),\n]\n","sub_path":"words/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"184554618","text":"# Import the pygame library and initialise the game engine\r\nimport pygame,sys,random\r\nfrom pygame.locals import *\r\nfrom mage import Mage\r\nfrom Spell import Spell\r\nfrom Baddie import Baddie\r\npygame.init()\r\n\r\n# Define some colors\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nGREEN = (0, 255, 0)\r\nRED = (255, 0, 0)\r\nPLAYERSPEED = 5\r\nSPELLSPEED = 8\r\nhealth = 100\r\nSPELLDAMAGE = 10\r\nBADDIESPEED = 2\r\n\r\nWINDOWWIDTH = 700\r\nWINDOWHEIGHT = 700\r\n# Open a new window\r\nsize = (WINDOWWIDTH, WINDOWHEIGHT)\r\nscreen = pygame.display.set_mode(size)\r\npygame.display.set_caption(\"Wizard Wars\")\r\n\r\n#set up font\r\nfont = pygame.font.SysFont(None, 48)\r\nfont2 = pygame.font.SysFont(None, 32)\r\n\r\n#functions\r\ndef waitForPlayerToPressKey():\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n terminate()\r\n if event.type == KEYDOWN:\r\n if event.key == K_ESCAPE: # pressing escape quits\r\n terminate()\r\n return\r\n\r\ndef drawText(text, font, surface, x, y):\r\n textobj = font.render(text, 1, WHITE)\r\n textrect = textobj.get_rect()\r\n textrect.topleft = (x, y)\r\n surface.blit(textobj, textrect)\r\n\r\n\r\n#This will be a list that will contain all the sprites we intend to use in our game.\r\nall_sprites_list = pygame.sprite.Group()\r\nbaddie_sprites_list = pygame.sprite.Group()\r\nspell_sprites_list = pygame.sprite.Group()\r\n\r\nplayerMage = Mage(BLACK,20,30)\r\nplayerMage.rect.x = 200\r\nplayerMage.rect.y = 300\r\nall_sprites_list.add(playerMage)\r\n# The loop will carry on until the user exit the game (e.g. clicks the close button).\r\ncarryOn = True\r\n\r\n\r\n# The clock will be used to control how fast the screen updates\r\nclock = pygame.time.Clock()\r\nspell = []\r\ndirection = []\r\nkills = 0\r\nbaddies = []\r\nmax_Baddies= 10\r\nbaddie_Counter = 0\r\nprevious_time = pygame.time.get_ticks()\r\ndrawText('Wizard Wars', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))\r\ndrawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)\r\ndrawText('aswd to shoot.', font, screen, (WINDOWWIDTH / 3) - 30, WINDOWHEIGHT-300)\r\ndrawText('arrows to move.', font, screen, (WINDOWWIDTH / 3) - 30, WINDOWHEIGHT-200)\r\npygame.display.update()\r\nwaitForPlayerToPressKey()\r\n# -------- Main Program Loop -----------\r\nwhile carryOn:\r\n facing = \"\"\r\n cast = 0\r\n moveLeft = moveRight = moveUp = moveDown = False\r\n # --- Main event loop\r\n for event in pygame.event.get(): # User did something\r\n if event.type == pygame.QUIT: # If user clicked close\r\n carryOn = False # Flag that we are done so we exit this loop\r\n elif event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_x: #Pressing the x Key will quit the game\r\n carryOn=False\r\n \r\n #while running:\r\n keys = pygame.key.get_pressed() #checking pressed keys\r\n if keys[pygame.K_UP] and playerMage.rect.y >=0:\r\n playerMage.moveUp(5)\r\n if keys[pygame.K_DOWN] and playerMage.rect.y <=WINDOWHEIGHT:\r\n playerMage.moveDown(5)\r\n if keys[pygame.K_LEFT] and playerMage.rect.x >=0:\r\n playerMage.moveLeft(5)\r\n if keys[pygame.K_RIGHT] and playerMage.rect.x <=WINDOWWIDTH:\r\n playerMage.moveRight(5)\r\n\r\n #use the aswd keys to shoot\r\n keyss = pygame.key.get_pressed()\r\n if keyss[pygame.K_a]:\r\n facing = \"w\"\r\n cast = 1\r\n if keyss[pygame.K_s]:\r\n facing = \"s\"\r\n cast = 1\r\n if keyss[pygame.K_w]:\r\n facing = \"n\"\r\n cast = 1\r\n if keyss[pygame.K_d]:\r\n facing = \"e\"\r\n cast = 1\r\n \r\n if cast == 1: \r\n current_time = pygame.time.get_ticks()\r\n if current_time - previous_time > 500:\r\n playerSpell = Spell(BLACK,20,30)\r\n playerSpell.rect.x = playerMage.rect.x\r\n playerSpell.rect.y = playerMage.rect.y\r\n all_sprites_list.add(playerSpell)\r\n spell.append(playerSpell)\r\n direction.append(facing)\r\n #all_sprites_list.add(playerSpell)\r\n spell_sprites_list.add(playerSpell)\r\n previous_time = current_time\r\n facing = \"\"\r\n\r\n for s, d in zip(spell, direction):\r\n if d == \"n\":\r\n s.castUp(SPELLSPEED)\r\n if s.rect.y >= WINDOWHEIGHT:\r\n spell.remove(s)\r\n direction.remove(d)\r\n spell_sprites_list.remove(s)\r\n if d == \"s\":\r\n s.castDown(SPELLSPEED)\r\n if s.rect.y <= 0:\r\n spell.remove(s)\r\n direction.remove(d)\r\n spell_sprites_list.remove(s)\r\n if d == \"e\":\r\n s.castRight(SPELLSPEED)\r\n if s.rect.x >= WINDOWWIDTH:\r\n spell.remove(s)\r\n direction.remove(d)\r\n spell_sprites_list.remove(s)\r\n if d == \"w\":\r\n s.castLeft(SPELLSPEED)\r\n \r\n ##move baddie to player\r\n for b in baddie_sprites_list:\r\n if b.rect.x > playerMage.rect.x:\r\n b.moveLeft(BADDIESPEED)\r\n if b.rect.x < playerMage.rect.x:\r\n b.moveRight(BADDIESPEED)\r\n if b.rect.y < playerMage.rect.y:\r\n b.moveDown(BADDIESPEED)\r\n if b.rect.y > playerMage.rect.y:\r\n b.moveUp(BADDIESPEED)\r\n\r\n #adding baddies\r\n if baddie_Counter <= max_Baddies:\r\n if random.randrange(0, 100)<1:\r\n if kills > 10:\r\n newBaddie = Baddie(RED,100,100,30)\r\n newBaddie.rect.x = random.randrange(0,WINDOWWIDTH)\r\n newBaddie.rect.y = 0\r\n baddie_sprites_list.add(newBaddie)\r\n baddie_Counter += 1\r\n else:\r\n newBaddie = Baddie(RED,50,50,10)\r\n newBaddie.rect.x = random.randrange(0,WINDOWWIDTH)\r\n newBaddie.rect.y = random.randrange(0,WINDOWHEIGHT)\r\n baddie_sprites_list.add(newBaddie)\r\n baddie_Counter += 1\r\n \r\n \r\n \r\n \r\n all_sprites_list.update()\r\n baddie_sprites_list.update()\r\n spell_sprites_list.update()\r\n\r\n #adding to kill counter and removing baddies\r\n prev = len(baddie_sprites_list)\r\n for b in baddie_sprites_list:\r\n baddie_collision_list = pygame.sprite.spritecollide(b,spell_sprites_list,True,pygame.sprite.collide_mask)\r\n for baddie in baddie_collision_list:\r\n b.health -= SPELLDAMAGE\r\n if b.health <=0:\r\n baddie_Counter-=1\r\n baddie_sprites_list.remove(b)\r\n pygame.sprite.groupcollide(spell_sprites_list, baddie_sprites_list, True, False)\r\n\r\n cur = len(baddie_sprites_list)\r\n kills+=(prev-cur)\r\n #checking to see if a baddie has collided with the mage\r\n mage_collision_list = pygame.sprite.spritecollide(playerMage,baddie_sprites_list,False,pygame.sprite.collide_mask)\r\n for mage in mage_collision_list:\r\n print(\"Dead\")\r\n #End Of Game\r\n carryOn=False\r\n\r\n \r\n \r\n \r\n # --- Drawing code should go here\r\n # First, clear the screen to white. \r\n screen.fill(BLACK)\r\n drawText('kills: %s' % (kills), font2, screen, 10, 0)\r\n\r\n #draw all the sprites\r\n all_sprites_list.draw(screen)\r\n baddie_sprites_list.draw(screen)\r\n spell_sprites_list.draw(screen)\r\n # --- Go ahead and update the screen with what we've drawn.\r\n pygame.display.flip()\r\n \r\n # --- Limit to 60 frames per second\r\n clock.tick(60)\r\n\r\n#Once we have exited the main program loop we can stop the game engine:\r\npygame.quit()\r\n","sub_path":"FinalProject/wizardwars.py","file_name":"wizardwars.py","file_ext":"py","file_size_in_byte":7556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"359097469","text":"import yaml\nimport json\nimport base64\n#from ruamel.yaml import YAML\nimport requests\n\n\ndef test_get_access_token():\n client_id = '2ph676ka96q2h7j163tienpbaa'\n client_secret = '199jnnko86u604bgbfkhojqh0afv9s69pg2da79d5pbpkrp9aopf'\n url = 'https://labrochure-test.auth.us-east-1.amazoncognito.com'\n path = '/oauth2/token?grant_type=client_credentials&users/users.create'\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': generate_authorization_header(client_id, client_secret),\n }\n #response = requests.post(url+path, headers=headers)\n #print(response.json())\n #assert 'access_token' in response.json()\n #assert response.headers['Content-Type'] == \"application/json\"\n #assert response.status_code == 200\n\n\n\ndef main():\n url = 'http://127.0.0.1:5000/test/oauth'\n #myobj = {'somekey': 'somevalue'}\n\n x = requests.get(url)\n #assert response.status_code == 200\n #print(dir(x))\n #print(type(x.text))\n #print(type(\"success\"))\n \n print('連線成功')\n #print(type(x))\n print('測試主機URL:',x.url)\n\n y = requests.get(x.text.replace(\"\\\"\", \"\").strip())\n\n print('授權主機URL:',y.url)\n\n print('授權呼叫授權主機成功:',y.url)\n\n payload = {'username': 'username', 'password': 'password'}\n z = requests.get(y.text.replace(\"\\\"\", \"\").strip(), params=payload)\n\n\n \n print('登入狀態:',z.text)\n\n \n\n \n \n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"110799631","text":"a = [3, 5, -4, 8, 11, 1, -1, 6, 5, 5, 4, 6]\nn = len(a)\n\ntargetsum = 10\n\n# method - 1\ntable = {}\npairs = []\n\nfor i in range(0,n):\n diff = targetsum - a[i]\n if diff in table:\n pairs.append([a[i], diff])\n del table[diff]\n else :\n table[a[i]] = True\n \nprint(pairs)\n\n# method - 2\npairs = []\na.sort()\n\ni = 0\nj = n-1\n\nwhile i < j :\n sum = a[i] + a[j]\n if sum == targetsum :\n pairs.append([a[i], a[j]])\n i = i + 1\n j = j - 1\n elif sum > targetsum :\n j = j - 1\n else :\n i = i + 1\n \nprint(pairs) \n \n \n \n ","sub_path":"python/twoNumberSum.py","file_name":"twoNumberSum.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"559693565","text":"import re\nimport json\n\nTWITTER_RE = re.compile('https?:\\/\\/twitter\\.com')\n\ndef is_twitter_url(url):\n return TWITTER_RE.match(url) is not None\n\ndef try_load_json(path):\n try:\n with open(path, 'r') as f:\n return json.load(f)\n except FileNotFoundError:\n return {}\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"584405457","text":"import argparse\nimport os\nimport re\nimport logging\n\nfrom pydub import AudioSegment\nfrom tqdm import tqdm\n\nALHPANUMERIC = re.compile(r\"\\W+\")\n\n\nclass Label:\n def __init__(self, word, start, end):\n self.word = word\n self.start = start\n self.end = end\n\n\ndef load_audio(audio_path, sample_rate):\n if audio_path.endswith(\"wav\"):\n audio = AudioSegment.from_wav(audio_path)\n else:\n audio = AudioSegment.from_mp3(audio_path)\n audio = audio.set_frame_rate(sample_rate)\n audio = audio.set_channels(1)\n return audio\n\n\ndef load_text_file_words(text_file_path):\n with open(text_file_path) as f:\n text = f.read()\n text = text.replace(\"\\n\", \" \")\n text = text.replace(\"-\", \" \")\n text = text.replace(\"...\", \"... \")\n return [item for item in text.split(\" \") if re.sub(ALHPANUMERIC, \"\", item)]\n\n\ndef load_forced_alignment_data(forced_alignment_path, text):\n successfully_aligned_words = 0\n sections = []\n section = []\n\n with open(forced_alignment_path, \"r\", encoding=\"utf-8\") as f:\n rows = f.readlines()\n for i in range(len(rows)):\n row = rows[i]\n word, guess, start, end = row.strip().split(\",\")\n assert re.sub(ALHPANUMERIC, \"\", word) == re.sub(\n ALHPANUMERIC, \"\", text[i]\n ), f\"{word} != {text[i]} on line {i+1}\"\n if word.lower() == guess.lower():\n successfully_aligned_words += 1\n section.append(Label(text[i], float(start), float(end)))\n elif section:\n sections.append(section)\n section = []\n\n if section:\n sections.append(section)\n print(f\"{successfully_aligned_words}/{len(rows)} successfully aligned\")\n return sections\n\n\ndef create_audio_snippet(audio, start, end, silence, output_folder):\n # Convert to ms\n name = f\"{start}_{end}.wav\"\n snippet = audio[start:end]\n # Pad with silence at the end\n snippet += silence\n # Save\n output_path = os.path.join(output_folder, name)\n snippet.export(output_path, format=\"wav\")\n return name\n\n\ndef clip_generator(\n audio_path,\n text_path,\n forced_alignment_path,\n output_path,\n label_path,\n logging=logging,\n min_length=1.0,\n max_length=10.0,\n gap=0.7,\n next_word_padding=0.0,\n silence_padding=0.1,\n sample_rate=22050,\n):\n os.makedirs(output_path, exist_ok=True)\n silence = AudioSegment.silent(duration=int(silence_padding * 1000))\n\n # Load data\n text = load_text_file_words(text_path)\n sections = load_forced_alignment_data(forced_alignment_path, text)\n\n logging.info(\"Loading audio...\")\n audio = load_audio(audio_path, sample_rate)\n logging.info(\"Loaded audio\")\n\n # Output variables\n clip_lengths = []\n result = {}\n\n total = len(sections)\n counter = 0\n\n for section in sections:\n sentence = []\n\n for i in range(len(section)):\n label = section[i]\n sentence.append(label)\n start = sentence[0].start\n length = sentence[-1].end - start\n gap_between_last_word = sentence[-1].start - sentence[-2].end if len(sentence) > 1 else 0\n\n # End snippet if last word, there was a large gap or it's getting too long\n if i == len(section) - 1 or gap_between_last_word > gap or length >= max_length:\n # Cutoff last word\n if gap_between_last_word > gap or length >= max_length:\n sentence = sentence[:-1]\n length = sentence[-1].end - start\n\n if length >= min_length:\n # Save snippet\n clip_lengths.append(length)\n start = int(start * 1000)\n end = int(sentence[-1].end * 1000) + int(next_word_padding * 1000)\n name = create_audio_snippet(audio, start, end, silence, output_path)\n result[name] = \" \".join([l.word for l in sentence])\n\n # Reset running variable\n sentence = [label]\n\n counter += 1\n logging.info(f\"Progress - {counter}/{total}\")\n\n # Save text file\n with open(label_path, \"w\", encoding=\"utf-8\") as f:\n for key, value in result.items():\n f.write(f\"{key}|{value}\\n\")\n\n return clip_lengths\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Split audio into snippets using forced align timings\")\n parser.add_argument(\"-a\", \"--audio_path\", help=\"Path to WAV file\", type=str, required=True)\n parser.add_argument(\"-t\", \"--text_path\", help=\"Path to source text file\", type=str, required=True)\n parser.add_argument(\n \"-f\", \"--forced_alignment_path\", help=\"Path to forced alignment CSV\", type=str, default=\"align.csv\"\n )\n parser.add_argument(\"-o\", \"--output_path\", help=\"Path to save snippets\", type=str, default=\"wavs\")\n parser.add_argument(\n \"-l\", \"--label_path\", help=\"Path to save snippet labelling text file\", type=str, default=\"metadata.csv\"\n )\n parser.add_argument(\"--min_length\", help=\"Minumum snippet length\", type=float, default=1.0)\n parser.add_argument(\"--max_length\", help=\"Maximum snippet length\", type=float, default=10.0)\n parser.add_argument(\"--gap\", help=\"Maximum gap between words for snippet to end\", type=float, default=0.7)\n parser.add_argument(\n \"--next_word_padding\", help=\"Additional gap from end of this word to next\", type=float, default=0.0\n )\n parser.add_argument(\"--silence_padding\", help=\"Silence padding on the end of the clip\", type=int, default=0.1)\n parser.add_argument(\"--sample_rate\", help=\"Audio sample rate\", type=int, default=22050)\n args = parser.parse_args()\n\n clip_lengths = clip_generator(**args)\n\n total_audio = sum(clip_lengths)\n total_clips = len(clip_lengths)\n minutes = int(total_audio / 60)\n seconds = total_audio - (minutes * 60)\n print(f\"Total clips = {total_clips} (average of {total_audio/total_clips} seconds per clip)\")\n print(f\"Total audio = {minutes} minutes, {seconds} seconds\")\n print(f\"Audio saved to {args.output_path}. Text file save to {args.label_path}\")\n\n import matplotlib.pyplot as plt\n\n plt.hist(clip_lengths, bins=10)\n plt.show()\n","sub_path":"research/forced_alignment/clip_generator_gentle.py","file_name":"clip_generator_gentle.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"177418918","text":"from __future__ import absolute_import\n\nimport os\nimport sys\n\nimport click\nimport six\n\nfrom ..commands import Command\nfrom ..exceptions import MPilotError, ProgramError\nfrom ..program import Program\n\nLINE_CONTEX_LENGTH = 3\n\n\n@click.command()\n@click.argument(\"library\")\n@click.argument(\"path\")\ndef main(library, path):\n if not os.path.exists(path):\n sys.stderr.write(\n \"\\n\".join(\n (\n \"Problem: The specified command file does not exist: {}\".format(path),\n \"Solution: Check the path to the command file and try again.\",\n )\n )\n )\n sys.stderr.write(\"\\n\")\n sys.exit(-1)\n\n with open(path) as f:\n lines = [line.strip(\"\\n\\r\") for line in f.readlines()]\n source = \"\\n\".join(lines)\n\n Command.load_commands(\"mpilot.libraries.eems.basic\")\n if library == \"eems-csv\":\n Command.load_commands(\"mpilot.libraries.eems.csv\")\n elif library == \"eems-netcdf\":\n Command.load_commands(\"mpilot.libraries.eems.netcdf\")\n\n try:\n program = Program.from_source(source)\n program.run()\n except MPilotError as ex:\n sys.stderr.write(\"\\n\".join((\"ERROR: There was a problem running the MPilot command file.\", six.text_type(ex))))\n sys.stderr.write(\"\\n\")\n\n if isinstance(ex, ProgramError) and ex.lineno is not None:\n idx = ex.lineno - 1\n start = max(idx - LINE_CONTEX_LENGTH, 0)\n end = min(idx + LINE_CONTEX_LENGTH, len(lines))\n\n sys.stderr.write(\"\\n\".join((\" \" * 4 + line for line in lines[start:idx])))\n sys.stderr.write(\"\\n\")\n sys.stderr.write(\"--> {}\".format(lines[idx]))\n sys.stderr.write(\"\\n\")\n sys.stderr.write(\"\\n\".join((\" \" * 4 + line for line in lines[idx + 1 : end])))\n sys.stderr.write(\"\\n\")\n\n sys.exit(-1)\n","sub_path":"mpilot/cli/mpilot.py","file_name":"mpilot.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616845016","text":"#!/usr/bin/python\n\nfrom Tkinter import *\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nimport matplotlib.animation as animation\nfrom matplotlib import style\n\n\nstyle.use('ggplot')\nd = Figure(figsize=(1,1), dpi=130)\na = d.add_subplot(111)\ne = Figure(figsize=(1,1), dpi=130)\nb = e.add_subplot(111)\nf = Figure(figsize=(1,1), dpi=130)\nc = f.add_subplot(111)\ng = Figure(figsize=(1,1), dpi=130)\nz = g.add_subplot(111)\n\ndataVariables = ['SV',\n 'SC',\n 'ST',\n 'AT',\n 'INT_V',\n 'INT_C',\n 'PS_H',\n 'PS_L',\n 'FAN_RPM',\n 'TT',\n 'SFD_1',\n 'EXT_V',\n 'EXT_C',\n 'SFD_2',\n 'CUT_V',\n 'OC_V',\n 'OC_T',\n 'SLEEP',\n 'ON/OFF', \n 'ACI', \n 'DC_TV',\n 'DIPI_1',\n 'DC_AV',\n 'DIPI_2',\n 'DATA',\n 'TIME',\n 'EXT_B',\n 'SYS',\n 'MAX_P',\n 'LAST_ERR',\n 'RT_S',\n 'INTB_AC',\n 'T_BATCHARGE']\n\ncurrentData = []\nvoltageData = []\ntemperatureData = []\npowerData = []\ndata = []\n\ndef getData():\n global dataVariables\n global data\n with open('data.txt', 'r') as f:\n data = eval(f.read())\n a = ''\n for i in dataVariables:\n if dataVariables.index(i) % 5 == 0 and dataVariables.index(i) != 0:\n a += '\\n'\n if len(i + ' : ' + data[i]) < 12:\n a += (i + ' : ' + data[i] + ' \\t\\t')\n else:\n a += (i + ' : ' + data[i] + '\\t\\t')\n return a\n\ndef animateCurrent(i):\n #if app.currentGraph.get_visible():\n currentData.append(float(data['SC'].strip('A'))) \n a.clear()\n a.plot([i for i in range(len(currentData))], currentData)\n app.currentGraph.draw()\n\ndef animateVoltage(i):\n #if app.voltageGraph.get_visible():\n voltageData.append(float(data['SV'].strip('V')))\n b.clear()\n b.plot([i for i in range(len(voltageData))], voltageData)\n app.voltageGraph.draw()\n\ndef animateTemperature(i):\n #if app.temperatureGraph.get_visible():\n temperatureData.append(float(data['ST'].strip('C').strip('+')))\n c.clear()\n c.plot([i for i in range(len(temperatureData))], temperatureData)\n app.temperatureGraph.draw()\n\ndef animatePower(i):\n powerData = [x*y for x, y in zip(currentData, voltageData)]\n z.clear()\n z.plot([i for i in range(len(powerData))], powerData)\n\ndef clearData():\n global temperatureData, currentData, voltageData\n temperatureData = []\n currentData = []\n voltageData = []\n \nclass Application(Frame):\n #swap between the graphs....\n def toggleGraph(self, type):\n if type == 'current':\n self.voltageGraph.get_tk_widget().pack_forget()\n self.temperatureGraph.get_tk_widget().pack_forget()\n #self.temperatureGraph.get_tk_widget().set_visible(False)\n self.currentGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n elif type == 'voltage':\n self.currentGraph.get_tk_widget().pack_forget()\n self.temperatureGraph.get_tk_widget().pack_forget()\n #self.currentGraph.get_tk_widget().set_visible(False)\n #self.temperatureGraph.get_tk_widget().set_visible(False)\n self.voltageGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n elif type == 'temperature':\n self.currentGraph.get_tk_widget().pack_forget()\n self.voltageGraph.get_tk_widget().pack_forget()\n #self.currentGraph.get_tk_widget().set_visible(False)\n #self.voltageGraph.get_tk_widget().set_visible(False)\n self.temperatureGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n\n def switchOn(self):\n print('switching on the button here...')\n\n def switchOff(self):\n print('switching off the button here....')\n\n def updateData(self):\n self.dataLog['text'] = getData()\n self.dataLog.after(1000, self.updateData)\n\n def start(self):\n clearData()\n print('starting something here....')\n\n def clear(self):\n clearData()\n print('cleared data')\n\n def createWidgets(self):\n self.dataLog = Label(self)\n self.dataLog['text'] = 'Hello lololololoo'\n self.dataLog['justify'] = LEFT\n self.dataLog['anchor'] = W\n self.dataLog['bg'] = 'green'\n self.dataLog.pack(side=TOP, fill=BOTH, expand=True)\n self.dataLog.after(1000, self.updateData)\n\n self.graphFrame = Frame(self)\n self.graphFrame['bg'] = 'red'\n self.graphFrame['width'] = 500\n self.graphFrame['height'] = 500\n self.graphFrame.pack(fill=BOTH, expand=True)\n\n self.buttonBar = Frame(self)\n self.buttonBar['bg'] = 'blue'\n self.buttonBar['height'] = 40\n self.buttonBar.pack(fill=X)\n self.buttonBar.pack_propagate(0)\n\n self.currentButton = Button(self.buttonBar)\n self.currentButton['text'] = 'Current'\n self.currentButton['command'] = lambda: self.toggleGraph('current')\n self.currentButton.pack(side=RIGHT, fill=BOTH)\n\n self.voltageButton = Button(self.buttonBar)\n self.voltageButton['text'] = 'Voltage'\n self.voltageButton['command'] = lambda: self.toggleGraph('voltage')\n self.voltageButton.pack(side=RIGHT, fill=BOTH)\n \n self.tempButton = Button(self.buttonBar)\n self.tempButton['text'] = 'Temperature'\n self.tempButton['command'] = lambda: self.toggleGraph('temperature')\n self.tempButton.pack(side=RIGHT, fill=BOTH)\n \n self.toolbar = Frame(self)\n self.toolbar['width'] = 500\n self.toolbar['bg'] = 'yellow'\n self.toolbar.pack(fill = X)\n\n self.switchOnButton = Button(self.toolbar)\n self.switchOnButton['text'] = 'Turn on'\n self.switchOnButton['command'] = self.switchOn\n self.switchOnButton.pack(side=LEFT)\n\n self.switchOffButton = Button(self.toolbar)\n self.switchOffButton['text'] = 'Turn off'\n self.switchOffButton['command'] = self.switchOff\n self.switchOffButton.pack(side=RIGHT)\n \n self.startButton = Button(self.toolbar)\n self.startButton['text'] = 'Start'\n self.startButton['command'] = self.start\n self.startButton.pack(side=LEFT)\n\n self.clearButton = Button(self.toolbar)\n self.clearButton['text'] = 'Clear'\n self.clearButton['command'] = self.clear\n self.clearButton.pack(side=LEFT)\n\n self.currentGraph = FigureCanvasTkAgg(d, self.graphFrame)\n self.currentGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n self.voltageGraph = FigureCanvasTkAgg(e, self.graphFrame)\n self.voltageGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n self.temperatureGraph = FigureCanvasTkAgg(f, self.graphFrame)\n self.temperatureGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n self.powerGraph = FigureCanvasTkAgg(g, self.graphFrame)\n self.powerGraph.get_tk_widget().pack(fill=BOTH, expand=True)\n \n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.pack()\n self.createWidgets()\n\n\ngetData()\nroot = Tk()\napp = Application(master=root)\nanimateCurrent = animation.FuncAnimation(d, animateCurrent, interval=1000)\nanimateVoltage = animation.FuncAnimation(e, animateVoltage, interval=1000)\nanimateTemperature = animation.FuncAnimation(f, animateTemperature, interval=1000)\nanimatePower = animation.FuncAnimation(g, animatePower, interval=1000)\napp.mainloop()\nroot.destroy()\n\n'''\ndef animate(i):\n print('called')\n pullData = open('sampleText.txt','r').read()\n dataArray = pullData.split('\\n')\n xar=[]\n yar=[]\n for eachLine in dataArray:\n if len(eachLine)>1:\n x,y = eachLine.split(',')\n xar.append(int(x))\n yar.append(int(y))\n a.clear()\n a.plot(xar,yar)\n app.currentGraph.draw()\n app.voltageGraph.draw()\n app.temperatureGraph.draw()\n'''","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":8346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"645125271","text":"__author__ = 'Mackenzie'\r\n__author__ = 'Mackenzie'\r\n\"\"\"\r\n Author: Mackenzie Larson\r\n\r\n Description: The program reads a sequence of integers and fixes inversion, until the numbers\r\n are sorted from smallest to largest, based on user's input.\r\n\r\n This lab is used as the basis for lab09a.py\r\n\"\"\"\r\n\r\nRED = '\\033[91m'\r\nEND = '\\033[0m'\r\n\r\nfrom graphics import *\r\nfrom time import sleep\r\n\r\nG_WINDOW_WIDTH = 1400\r\nG_WINDOW_HEIGHT = 800\r\nBASE_LINE_Y = G_WINDOW_HEIGHT - 50\r\nGAP_BETWEEN_RECTANGLES = 4\r\nHEIGHT_MULTIPLIER = 2\r\nRECTANGLE_WIDTH = 20\r\n\r\nseq1_points = [17, 177, 72, 273, 37, 341, 152, 282, 180, 250, 31, 10, 39, 33, 204, 154,\r\n 11, 55, 178, 202, 144, 247, 220, 148, 22, 137, 306, 271, 111, 236,\r\n 85, 169, 147, 214, 196, 20, 50, 30, 240, 275, 139, 215, 319, 15,\r\n 21, 107, 90, 69, 280, 140, 19]\r\n\r\n\r\nseq1_points = [17, 177, 72, 273, 37, 341, 152, 282, 180, 250, 31, 10, 39, 33, 204, 154,\r\n 11, 55, 178, 202, 144, 247, 220, 148, 22, 137]\r\n\r\n\r\ndef create_and_draw_rectangles(numbers, win):\r\n rectangles = []\r\n bar = Rectangle(Point(4, BASE_LINE_Y - numbers[0] * HEIGHT_MULTIPLIER) , Point(24, BASE_LINE_Y))\r\n bar.setFill('yellow')\r\n bar.draw(win)\r\n rectangles.append(bar)\r\n\r\n for i in range(1, len(numbers)):\r\n bar = Rectangle(Point(4 ,BASE_LINE_Y - numbers[i] * HEIGHT_MULTIPLIER), Point(24,BASE_LINE_Y))\r\n bar.move(i * (GAP_BETWEEN_RECTANGLES + RECTANGLE_WIDTH), 0)\r\n rectangles.append(bar)\r\n bar.setFill('yellow')\r\n bar.draw(win)\r\n\r\n return rectangles\r\n\r\ndef find_selected_rectangle(c_point,rectangles):\r\n\r\n click_point_x = c_point.getX()\r\n click_point_y = c_point.getY()\r\n for i in range(len(rectangles)):\r\n x1 = rectangles[i].getP1().getX()\r\n y1 = rectangles[i].getP1().getY()\r\n x2 = rectangles[i].getP2().getX()\r\n y2 = rectangles[i].getP2().getY()\r\n if click_point_x > x1 and click_point_x < x2:\r\n if click_point_y > y1 and click_point_y < y2:\r\n rectangles[i].setFill('dark blue')\r\n sleep(.095)\r\n return i\r\n return None\r\n\r\ndef identify_rect_inversions(rectangles, numbers, win):\r\n\r\n for i in range (len(rectangles)):\r\n if i == 0:\r\n rectangles[i].setFill('yellow')\r\n if i > 0:\r\n if numbers[i] < numbers [i - 1]:\r\n rectangles[i].setFill('red')\r\n win.update()\r\n else:\r\n rectangles[i].setFill('yellow')\r\n win.update()\r\n return\r\n\r\n\r\n \"\"\"\r\n Color the rectangles in rectangles that represent an inversion in numbers in red.\r\n\r\n rectangles: a list of rectangles.\r\n numbers: a list of numbers. When defined, rectangles[i] represents numbers[i].\r\n\r\n return value: None\r\n \"\"\"\r\n\r\ndef get_num_values():\r\n global seq1_points\r\n return len(seq1_points)\r\n\r\n\r\ndef get_value():\r\n global seq1_points\r\n for point in seq1_points:\r\n yield point\r\n yield None\r\n\r\n\r\ndef next_value():\r\n return next(next_value.points)\r\n\r\n\r\nnext_value.points = get_value()\r\n\r\n\r\ndef echo(numbers, in_red):\r\n \"\"\"\r\n Prints a list of numbers and their indices on one line.\r\n\r\n :param numbers: a list of integers to print\r\n :param in_red: inversion in \"numbers\" will be printed in red if \"in_red\" is True\r\n :return: None\r\n \"\"\"\r\n\r\n input_size = len(numbers)\r\n if input_size == 0:\r\n return # Nothing to print\r\n\r\n # print the indices\r\n print(end=\"|\")\r\n for i in range(input_size):\r\n print(str(i).rjust(4), sep=\"\", end=\"|\")\r\n print()\r\n\r\n # print the values in the list\r\n print(\"|\", str(numbers[0]).rjust(4), sep=\"\", end=\"|\")\r\n for i in range(1, input_size):\r\n if in_red:\r\n if numbers[i] < numbers[i - 1]:\r\n print(RED + str(numbers[i]).rjust(4) + END, sep=\"\", end=\"|\")\r\n else:\r\n print(str(numbers[i]).rjust(4), sep=\"\", end=\"|\")\r\n else:\r\n print(str(numbers[i]).rjust(4), sep=\"\", end=\"|\")\r\n\r\n print()\r\n\r\n\r\ndef count_inversions(numbers):\r\n \"\"\"\r\n Counts and returns the number of inversion in \"numbers\"\r\n\r\n :param numbers: a list of read-only numbers\r\n :return: the number of inversions\r\n \"\"\"\r\n\r\n input_size = len(numbers)\r\n inversions = 0\r\n for i in range(1, input_size):\r\n if numbers[i] < numbers[i - 1]:\r\n inversions += 1\r\n return inversions\r\n\r\n\r\ndef get_input():\r\n \"\"\"\r\n Using \"next_point()\", reads input values, stores them in a list, and returns the list.\r\n\r\n :return: a list of zero or more values; the values are expected to be integers\r\n \"\"\"\r\n p = next_value()\r\n numbers = []\r\n while p is not None:\r\n numbers.append(p)\r\n p = next_value()\r\n return numbers\r\n\r\n\r\ndef fix_left_inversion(pos, numbers, rectangles, win):\r\n \"\"\"\r\n Fixes an inversion whose index is in \"pos\" in the left direction.\r\n\r\n :param pos: the index of the inversion to fix\r\n :param numbers: a list of numbers possibly with numbers[pos-1] > numbers[pos]\r\n \"\"\"\r\n\r\n while pos > 0 and numbers[pos] < numbers[pos - 1]:\r\n rectangles[pos].move(-24, 0)\r\n rectangles[pos-1].move(24,0)\r\n\r\n numbers[pos-1], numbers[pos] = numbers[pos], numbers[pos-1]\r\n rectangles[pos-1], rectangles[pos] = rectangles[pos], rectangles[pos -1]\r\n\r\n\r\n win.update()\r\n pos -= 1\r\n\r\n\r\ndef fix_right_inversion(pos, numbers, rectangles, win):\r\n \"\"\"\r\n Fixes an inversion whose index is in \"pos\" in the right direction.\r\n\r\n :param pos: the index of the inversion to fix\r\n :param numbers: a list of numbers possibly with numbers[pos] > numbers[pos+1]\r\n \"\"\"\r\n\r\n num_list_elements = len(numbers)\r\n print(num_list_elements)\r\n print(len(rectangles))\r\n while pos < num_list_elements - 1 and numbers[pos] > numbers[pos + 1]:\r\n #print(pos)\r\n rectangles[pos].move(RECTANGLE_WIDTH + GAP_BETWEEN_RECTANGLES, 0)\r\n rectangles[pos+1].move(-RECTANGLE_WIDTH + GAP_BETWEEN_RECTANGLES,0)\r\n\r\n numbers[pos+1], numbers[pos] = numbers[pos], numbers[pos+1]\r\n rectangles[pos+1], rectangles[pos] = rectangles[pos], rectangles[pos +1]\r\n\r\n\r\n win.update()\r\n pos += 1\r\n\r\n\r\ndef fix_inversion(pos, numbers, rectangle, win):\r\n \"\"\"\r\n Fixes a left or a right inversion.\r\n\r\n :param pos: the index of the inversion to fix\r\n :param numbers: a list of integers with possibly an inversion at \"pos\"\r\n :param direction: \"left\" or \"right\"\r\n \"\"\"\r\n if pos > 0 and numbers[pos] < numbers[pos - 1]:\r\n fix_left_inversion(pos, numbers, rectangle, win)\r\n\r\n elif pos < len(numbers) - 1 and numbers[pos] > numbers[pos + 1]:\r\n fix_right_inversion(pos, numbers, rectangle, win)\r\n\r\ndef find_an_inversion(numbers):\r\n for i in range(1, len(numbers)):\r\n if numbers[i] < numbers[i-1]:\r\n return i\r\n\r\ndef main():\r\n \"\"\"\r\n Reads a list of integers and then repeatedly fixes inversion based on user's input.\r\n\r\n \"\"\"\r\n\r\n numbers = get_input()\r\n win = GraphWin(\"Lab09b\", G_WINDOW_WIDTH, G_WINDOW_HEIGHT)\r\n rectangles = create_and_draw_rectangles(numbers,win)\r\n identify_rect_inversions(rectangles, numbers, win)\r\n\r\n for i in range (len(numbers)+1):\r\n center_of_text = Point(i * 24-9, BASE_LINE_Y + 10)\r\n text_to_display = Text(center_of_text, str(i-1))\r\n text_to_display.setSize(8)\r\n text_to_display.setTextColor(\"black\")\r\n text_to_display.draw(win)\r\n\r\n win.getMouse()\r\n\r\n\r\n #echo(numbers, True)\r\n inversions = count_inversions(numbers)\r\n print(\"\\nThere are\", inversions, \"inversions.\\n\")\r\n\r\n while inversions > 0:\r\n\r\n pos = find_an_inversion(numbers)\r\n fix_inversion(pos, numbers, rectangles, win)\r\n identify_rect_inversions(rectangles, numbers, win)\r\n inversions = count_inversions(numbers)\r\n\r\n win.update()\r\n win.getMouse()\r\n\r\n echo(numbers, True)\r\n\r\nmain()\r\n\r\n\r\n","sub_path":"CS115/Lab09/lab09d.py","file_name":"lab09d.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"13578849","text":"\"\"\"Query PubMed for list of IDs (PMIDs) of articles published each day\n\nInspired by https://github.com/pkerpedjiev/gene-citation-counts\n\"\"\"\n\nimport os\nimport re\nimport urllib.request as ur\nimport time\nfrom tqdm import tqdm\nimport argparse\nfrom datetime import date as dt_date, timedelta, datetime\n\nfrom lib import is_cached\n\ndef pmids_by_date(\n start_date=None, end_date=None,\n output_dir=\"gene_hints/data/tmp\",\n cache=0\n):\n \"\"\"Query PubMed for citation lists for each day\n \"\"\"\n\n # Get today's date\n today = dt_date.today().strftime(\"%Y/%m/%d\")\n\n if start_date == None:\n start_date = today\n if end_date == None:\n end_date = today\n\n # Format start and end date\n start_date = datetime.strptime(start_date, \"%Y/%m/%d\")\n end_date = datetime.strptime(end_date, \"%Y/%m/%d\")\n\n days = abs((start_date - end_date).days)\n print(\"Get data from the last \" + str(abs(days)) + \" days\")\n print(\"Output will go into: \" + output_dir)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n # Get start date\n date_itr = start_date\n\n eutils_base =\\\n \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed\"\n\n # Go through each day\n for i in tqdm(range(days)):\n\n date = datetime.strftime(date_itr, \"%Y/%m/%d\")\n date_itr += timedelta(days=1)\n\n # Create the citation lists per each day\n date_underscore = date.replace(\"/\", \"_\")\n\n output_path = f\"{output_dir}/{date_underscore}.tsv\"\n\n # Skip downloading file if cache level is set and cached file exists\n if is_cached(output_path, cache, 1):\n continue\n\n # Call NCBI E-utils / Entrez API\n # https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.mindate_maxdate\n link = f\"{eutils_base}&mindate={date}&maxdate={date}&retmax=100000\"\n time.sleep(1.5)\n fin = ur.urlopen(link)\n\n # Parse the result\n text = fin.read().decode(\"utf-8\")\n all_pmids = re.finditer(r\"(?P[0-9]+)\", text)\n date_pmid_lines = \"\"\n for pmid_match in all_pmids:\n date_hyphen = date.replace(\"/\", \"-\")\n pmid = pmid_match.group(\"pmid\")\n date_pmid_lines += date_hyphen + \"\\t\" + pmid + \"\\n\"\n\n with open(output_path, \"w\") as f:\n f.write(date_pmid_lines)\n\n print(\"Output to: \" + output_path)\n\n# Command-line handler\nif __name__ == \"__main__\":\n usage = \"\"\"\n python3 gene_hints/citations/pmids_by_date.py --start-date 2021/07/07 --end-date 2021/07/15 --output-dir gene_hints/data/tmp\n \"\"\"\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n usage=usage\n )\n\n # Set the time frame\n parser.add_argument(\n \"--start-date\",\n help=\"Recent end of the date range to search (YYYY/MM/DD)\"\n )\n parser.add_argument(\n \"--end-date\",\n help=\"Distant end the date range to search (YYYY/MM/DD)\"\n )\n\n parser.add_argument(\n \"--output-dir\",\n help=\"Directory to output files\"\n )\n\n args = parser.parse_args()\n\n pmids_by_date(args.start_date, args.end_date, args.output_dir)\n","sub_path":"gene_hints/citations/pmids_by_date.py","file_name":"pmids_by_date.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"106650323","text":"import kivy\r\nkivy.require(\"1.11.1\")\r\nfrom kivy.app import App\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.properties import StringProperty\r\n\r\nclass CountupWidget(Widget):\r\n\ttext = StringProperty()\r\n\r\n\tdef __init__(self, **kwargs):\r\n\t\tsuper(CountupWidget, self).__init__(**kwargs)\r\n\t\tself.text = \"\"\r\n\r\n\tdef buttonClicked(self):\r\n\t\tif not self.text.isdigit():\r\n\t\t\tself.text = str(0)\r\n\t\telse: \r\n\t\t\tself.text = str(int(self.text)+1)\r\n\r\nclass CountupApp(App):\r\n\tdef __init__(self, **kwargs):\r\n\t\tsuper(CountupApp, self).__init__(**kwargs)\r\n\t\tself.title = \"countup\"\r\n\r\n\tdef build(self):\r\n\t\treturn CountupWidget()\r\n\r\nif __name__ == \"__main__\":\r\n\tCountupApp().run()","sub_path":"countup.py","file_name":"countup.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"115370315","text":"import rasterio\nfrom shapely.geometry import Point, Polygon, LineString, mapping\nimport geopandas as gpd\n\n\ndef extract_gpd_geometry(point_gdf):\n \"\"\"\n Function to extract x, y, z coordinates and add as columns to input geopandas data frame.\n \"\"\"\n x = []\n y = []\n z = []\n for i in range(len(point_gdf)): \n x.append(point_gdf['geometry'].iloc[i].coords[:][0][0])\n y.append(point_gdf['geometry'].iloc[i].coords[:][0][1])\n z.append(point_gdf['geometry'].iloc[i].coords[:][0][2])\n\n point_gdf['x'] = x\n point_gdf['y'] = y\n point_gdf['z'] = z\n\ndef polygon_gdf_to_coordiantes(polygon_gdf):\n geometries = [i for i in polygon_gdf.geometry]\n all_coords = mapping(geometries[0])[\"coordinates\"]\n return all_coords\n \ndef geotif2polygon(geotif_name):\n \"\"\"\n Function to return polygon geodataframe matching the extent and coordinate system of the input geotif.\n \"\"\"\n\n # read in dem using rasterio\n geotif = rasterio.open(geotif_name)\n\n # extact total bounds of dem\n bbox = geotif.bounds\n\n # convert to corner points\n p1 = Point(bbox[0], bbox[3])\n p2 = Point(bbox[2], bbox[3])\n p3 = Point(bbox[2], bbox[1])\n p4 = Point(bbox[0], bbox[1])\n\n # extract corner coordinates\n np1 = (p1.coords.xy[0][0], p1.coords.xy[1][0])\n np2 = (p2.coords.xy[0][0], p2.coords.xy[1][0])\n np3 = (p3.coords.xy[0][0], p3.coords.xy[1][0])\n np4 = (p4.coords.xy[0][0], p4.coords.xy[1][0])\n\n # convert to polygon\n bb_polygon = Polygon([np1, np2, np3, np4])\n\n # create geodataframe\n geotif_polygon_gdf = gpd.GeoDataFrame(gpd.GeoSeries(bb_polygon), columns=['geometry'])\n\n geotif_polygon_gdf.crs = geotif.crs\n\n return geotif_polygon_gdf\n\n\ndef create_line(point0,point1):\n line = LineString([point0, point1])\n line = gpd.GeoDataFrame(gpd.GeoSeries(line),columns=['geometry'],crs='3857')\n return line\n \ndef df_points_to_polygon_gdf(df, \n lon='lon',\n lat='lat',\n z='elevation',\n crs='4326'):\n vertices = []\n\n for i in range(len(df)):\n vertex = (df[lon][i], df[lat][i], df[z][i])\n vertices.append(vertex)\n \n polygon = Polygon(vertices)\n polygon_gdf = gpd.GeoDataFrame(gpd.GeoSeries(polygon), \n columns=['geometry'],\n crs={'init':'epsg:'+crs}) \n\n return polygon_gdf\n\ndef extract_polygon_centers(gdf):\n gdf['polygon_center'] = gdf['geometry'].apply(lambda x: x.representative_point().coords[:])\n gdf['polygon_center'] = [coords[0] for coords in gdf['polygon_center']]\n return gdf\n \ndef df_xyz_coords_to_gdf(df, \n lon='lon',\n lat='lat',\n z='elevation',\n crs='4326'):\n\n geometry = [Point(xyz) for xyz in zip(df[lon], df[lat], df[z])] \n gdf = gpd.GeoDataFrame(gpd.GeoSeries(geometry), columns=['geometry'], crs={'init':'epsg:'+crs})\n \n return gdf\n \n ","sub_path":"bare/geospatial/geospatial.py","file_name":"geospatial.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"311691869","text":"# This script will take the data transcription tsv file from a dataset as an argument, and output wether IDs in the transcript\r\n# correspond to Bilingual or Monolingual data. A csv file will also be created containing a list of the results.\r\n# USAGE: Place this script in either the Train or the Dev folder (not necesary). Run using the system console and pass the .tsv file as argument.\r\n\r\nimport sys, re, csv\r\n\r\ninputFileName = sys.argv[1]\r\n\r\nmycvsfile = open('MonoBiClassification.csv',\"wt\", newline = '') # Create .csv to store clasification\r\nwr = csv.writer(mycvsfile, quoting=csv.QUOTE_ALL)\r\n\r\nwith open(inputFileName) as inputFile:\r\n for line in inputFile:\r\n lineList = re.split(r'\\t+',line)\r\n transcription = re.sub('[^A-Za-z0-9]+', '', lineList[1])\r\n firstChar = transcription[0]\r\n for c in transcription:\r\n if(c != firstChar):\r\n flag = 1\r\n break\r\n else: flag = 0\r\n\r\n if (flag == 1):\r\n print(\"\\n\" + lineList[0] + \"\\tBilingual\")\r\n csvline = (lineList[0],\"Bilingual\",lineList[1])\r\n wr.writerow(csvline)\r\n elif(flag == 0):\r\n print(\"\\n\" + lineList[0] + \"\\tMonolingual\")\r\n csvline = (lineList[0],\"Monolingual\",lineList[1])\r\n wr.writerow(csvline)\r\n else: print(\"\\n\" + lineList[0] + \"\\tERROR\")\r\n\r\nprint(\"...Done!\")","sub_path":"IdentifyMonoBi.py","file_name":"IdentifyMonoBi.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"301425412","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 6 15:31:14 2020\r\n\r\n@author: whip\r\n\"\"\"\r\n\r\n#pywinautoによる特定ウィンドウのスクリーンショット\r\nimport os\r\n#from pywinauto import application\r\nimport datetime\r\nfrom PIL import ImageGrab, Image\r\n\r\ndef screenshot_sinopc():\r\n \r\n now = datetime.datetime.now() \r\n today = create_todays_folder(now)\r\n timestamp = now.strftime(\"%Y-%m-%d %H_%M_%S\")\r\n img_name = 'image/'+today+'/sinopcsnapshot' + timestamp + '.png'\r\n \r\n img = ImageGrab.grab(bbox=[717,119,1203,983])\r\n print(\"保存します \",img_name)\r\n img.save(img_name)\r\n \r\n return img_name \r\n\r\ndef screenshot_sinopc_game_info():\r\n \r\n now = datetime.datetime.now() \r\n today = create_todays_folder(now)\r\n timestamp = now.strftime(\"%Y-%m-%d %H_%M_%S\")\r\n img_name = 'image/'+today+'/sinopcsnapshot' + timestamp + '.png'\r\n \r\n img = ImageGrab.grab(bbox=[717,119,1203,983])\r\n print(\"保存します \",img_name)\r\n img.save(img_name)\r\n \r\n img_cropped = img.crop((0,0,486,98)) #デフォルト位置でのスクショ?\r\n img_cropped_name = 'image/'+today+'/sinopc_game_info' + timestamp + '.png'\r\n print(\"保存します \",img_cropped_name)\r\n img_cropped.save(img_cropped_name)\r\n \r\n return img_cropped_name \r\n\r\n\r\ndef create_todays_folder(now):\r\n today = now.strftime(\"%Y%m%d\")\r\n new_dir_path =\"image/\"+today\r\n os.makedirs(new_dir_path, exist_ok=True)\r\n return today","sub_path":"archive_g/honu1.2/sinopcscreenshot.py","file_name":"sinopcscreenshot.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"383713969","text":"import datetime\n\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom my_browsing_history.models import *\nfrom log_in.models import *\ndef MyBrowsingHistory(request):\n if not request.session.has_key('userName'):\n return redirect('login')\n elif request.method == 'POST':\n pass\n else:\n userName = request.session.get('userName')\n context = {}\n try:\n aUser = user.objects.get(user_name=userName)\n context.update(imagePath=aUser.user_image.url)\n context.update(username=aUser.user_name)\n return render(request, 'my_browsing_history/IBrowsed.html',context)\n except:\n return render(request, 'my_browsing_history/IBrowsed.html', context)\nclass histroyshow(object):\n def __init__(self,date='',question_name='',question_id=0):\n self.date=date\n self.question_name=question_name\n self.question_id=question_id\ndef MyBrowsingHistoryInner(request):\n if not request.session.has_key('userName'):\n return redirect('login')\n username = request.session.get('userName')\n try:\n\n aUser = user.objects.get(user_name=username)\n historylist = aUser.history_set.order_by('-id')\n questionlist=[]\n for ahistory in historylist:\n question1 = ahistory.history_question_id\n a1 = histroyshow()\n a1.date= ahistory.history_date\n a1.question_name=question1.question_name\n a1.question_id=question1.pk\n questionlist.append(a1)\n context = {}\n context.update(username=username)\n context.update(questionlist=questionlist)\n return render(request,'my_browsing_history/inner_IBrowsed.html',context)\n except user.DoesNotExist:\n return redirect('login')\n\n\n\n","sub_path":"my_browsing_history/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"532161852","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/ftpysetup/cmdbuild/build_rglob.py\n# Compiled at: 2015-01-04 11:32:21\n# Size of source mod 2**32: 2419 bytes\n\"\"\"Enhance ``build_py`` to allow recursive directory globbing with ``**``.\"\"\"\n__author__ = ('Lance Finn Helsten', )\n__version__ = '0.7.3'\n__copyright__ = 'Copyright (C) 2014 Lance Helsten'\n__docformat__ = 'reStructuredText en'\n__license__ = '\\n Licensed under the Apache License, Version 2.0 (the \"License\");\\n you may not use this file except in compliance with the License.\\n You may obtain a copy of the License at\\n\\n http://www.apache.org/licenses/LICENSE-2.0\\n\\n Unless required by applicable law or agreed to in writing, software\\n distributed under the License is distributed on an \"AS IS\" BASIS,\\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n See the License for the specific language governing permissions and\\n limitations under the License.\\n'\n__all__ = [\n 'build_rglob']\nimport os\nfrom glob import glob\nfrom setuptools.command.build_py import build_py\nfrom distutils.util import convert_path\n\nclass build_rglob(build_py):\n __doc__ = 'Enhance ``build_py`` to allow recursive directory globbing with\\n ``**``.\\n '\n\n def find_data_files(self, package, src_dir):\n globs = self.package_data.get('', []) + self.package_data.get(package, [])\n globs = []\n for pattern in self.package_data.get('', []) + self.package_data.get(package, []):\n if '**' in pattern:\n globs.extend(self._build_rglob__expand_doublestar(src_dir, pattern))\n else:\n globs.append(pattern)\n\n files = self.manifest_files.get(package, [])[:]\n for pattern in globs:\n gpath = os.path.join(src_dir, convert_path(pattern))\n files.extend(glob(gpath))\n\n return self.exclude_data_files(package, src_dir, files)\n\n def __expand_doublestar(self, src_dir, pattern):\n ret = []\n prefix, suffix = pattern.split(sep='**', maxsplit=1)\n suffix = suffix.lstrip(os.sep)\n rootdir = os.path.join(src_dir, prefix)\n for dirpath, dirnames, filenames in os.walk(rootdir):\n path = os.path.join(dirpath, suffix)\n ret.append(path)\n\n ret = [d.replace(src_dir + os.sep, '') for d in ret]\n return ret","sub_path":"pycfiles/ftpysetup-0.7.3.macosx-10.10-x86_64.tar/build_rglob.cpython-34.py","file_name":"build_rglob.cpython-34.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"352095496","text":"def words(strng, dictionary):\n \n stringLen = len(strng)\n # if stringLen == 0:\n # return True\n\n for i in range(1,stringLen+1):\n prefix = strng[0:i]\n if prefix in [value for (key,value) in dictionary.items() if value==prefix]:\n print(prefix)\n words(strng[i:stringLen],dictionary)\n return True\n \n return False\n \nif __name__==\"__main__\":\n print('word break problem')\n dictionary = {\"0\":\"pitch\",\"1\":\"can\",\"2\":\"candy\",\"3\":\"rick\",\"4\":\"joby\",\"5\":\"smug\",\"6\":\"a\",\"7\":\"mass\"}\n print(words('pitchcandymass',dictionary))","sub_path":"Algorithms/DP/wordbreakproblem.py","file_name":"wordbreakproblem.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"175164270","text":"import pandas.util.testing as pdt\n\nfrom pyutil.mongo.engine.symbol import Symbol, Group\nfrom test.config import *\n\n\n@pytest.fixture()\ndef group():\n Group.objects.delete()\n return Group(name=\"US Equity\").save()\n\n\n@pytest.fixture()\ndef symbol(group):\n Symbol.objects.delete()\n\n symbol = Symbol(name='IBM US Equity', group=group, internal=\"IBM\")\n # you can add on the dictionary on the fly\n symbol.tags = ['mongodb', 'mongoengine']\n\n symbol.reference[\"XXX\"] = \"A\"\n symbol.reference[\"YYY\"] = \"B\"\n symbol.open = pd.Series(data=[1.1, 2.1, 3.1], name=\"test\")\n return symbol.save()\n\n\ndef test_symbol(group, symbol):\n assert len(Symbol.objects(tags='mongoengine')) == 1\n assert symbol.group == group\n\n frame = Symbol.reference_frame()\n assert frame.loc[\"IBM US Equity\"][\"XXX\"] == \"A\"\n assert Symbol.symbolmap() == {\"IBM US Equity\": \"US Equity\"}\n\n pdt.assert_series_equal(symbol.open, pd.Series(data=[1.1, 2.1, 3.1], name=\"test\"))\n\n with pytest.raises(AttributeError):\n symbol.px_last\n\n","sub_path":"test/test_mongo/test_engine/test_symbol.py","file_name":"test_symbol.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"228142978","text":"#------------------------------------------------------------------------------\n# Specifications\n#------------------------------------------------------------------------------\n# specify directories\ndir_wrfiles = \"/home/jovyan/DNN_ESANN_dev\" # for testing on DSRI\n#dir_wrfiles = r\"C:\\Users\\kiki.vanderheijden\\Documents\\PostDoc_Auditory\\DeepLearning\" # for testing locally\n\n# import libraries\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models # contains different types of models (use sequential model here?)\nfrom tensorflow.keras import optimizers # contains different types of back propagation algorithms to train the model, \n # including sgd (stochastic gradient\n#from CustLoss_MSE import cust_mean_squared_error # note that in this loss function, the axis of the MSE is set to 1\nfrom CustLoss_Combined_CosineAngular_MSE_weighed import cos_dist_angular_and_mse_weighed # note that in this loss function, the axis of the MSE is set to 1\nfrom CustMet_cosine_distance_angular import cos_distmet_2D_angular\n\n# specify parameters\nmodelname = 'model20'\ntime_sound = 2000 # input dimension 1 (time)\nnfreqs = 99 # input dimension 2 (frequencies)\n\n#------------------------------------------------------------------------------\n# Define model architecture\n#------------------------------------------------------------------------------\n# left channel\nin1 = layers.Input(shape=(time_sound,nfreqs,1)) # define input (rows, columns, channels (only one in my case))\nmodel_l_conv1 = layers.Conv2D(16,(1,3),activation='relu', padding = 'same')(in1) # define first layer and input to the layer\nmodel_l_conv1_mp = layers.MaxPooling2D(pool_size = (1,2))(model_l_conv1)\nmodel_l_conv1_mp_do = layers.Dropout(0.2)(model_l_conv1_mp)\n\n# right channel\nin2 = layers.Input(shape=(time_sound,nfreqs,1)) # define input\nmodel_r_conv1 = layers.Conv2D(16,(1,3),activation='relu', padding = 'same')(in2) # define first layer and input to the layer\nmodel_r_conv1_mp = layers.MaxPooling2D(pool_size = (1,2))(model_r_conv1)\nmodel_r_conv1_mp_do = layers.Dropout(0.2)(model_r_conv1_mp)\n\n# merged\nmodel_final_merge = layers.Concatenate(axis = -1)([model_l_conv1_mp_do, model_r_conv1_mp_do]) \nmodel_final_conv1 = layers.Conv2D(32,(3,3),activation='relu', padding = 'same')(model_final_merge)\nmodel_final_conv1_mp = layers.MaxPooling2D(pool_size = (2,2))(model_final_conv1)\nmodel_final_conv1_mp_do = layers.Dropout(0.2)(model_final_conv1_mp)\n\nmodel_final_flatten = layers.Flatten()(model_final_conv1_mp_do)\nmodel_final_dropout = layers.Dropout(0.2)(model_final_flatten) # dropout for regularization\npredicted_coords = layers.Dense(2, activation = 'tanh')(model_final_dropout) # I have used the tanh activation because our outputs should be between -1 and 1\n\n#------------------------------------------------------------------------------\n# Create model\n#------------------------------------------------------------------------------\n# create\nmodel = models.Model(inputs = [in1,in2], outputs = predicted_coords) # create\n# compile\nmodel.compile(loss = cos_dist_angular_and_mse_weighed, optimizer = optimizers.Adam(), metrics=['cosine_proximity','mse',cos_distmet_2D_angular])\n# print summary\nmodel.summary()\n# save\nmodel.save(dir_wrfiles+'/DNN_'+modelname+'.h5') # save model\n\n","sub_path":"architecture_CNN_MSE.py","file_name":"architecture_CNN_MSE.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"236602387","text":"from flask import request\nfrom flask import Flask, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\nfrom flask import render_template\nfrom sqlalchemy import create_engine\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:test@localhost/postgres'\nengine = create_engine('postgresql+psycopg2://postgres:test@localhost/postgres')\n\napp.debug = True\napp.config['SQLALCHEMY_ECHO'] = True\ndb=SQLAlchemy(app)\nBootstrap(app)\n\n# classes\n\nclass Sdctest(db.Model):\n quoteno= db.Column (db.Text, primary_key=True)\n cusname= db.Column (db.Text)\n chassistype1= db.Column (db.Text)\n sockets= db.Column(db.Text)\n axleqty= db.Column (db.Integer)\n\n\n\n#routes\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n options = db.session.query(Sdctest.chassistype1).distinct().all()\n axleopts = db.session.query(Sdctest.axleqty).distinct().all()\n # enables passing user input to the variable\n if request.method == 'POST':\n # query parameters and their corresponding database columns\n param_columns = {\n \"quoteno\": \"quoteno\",\n \"cusname\": \"cusname\",\n \"chassistype1\": \"chassistype1\",\n \"sockets\": \"sockets\",\n \"axleqty\": \"axleqty\"\n }\n # Get all of the column filters where the parameters aren't empty\n\n filters = {\n column: request.form[param]\n for param, column in param_columns.items()\n if request.form.get(param, \"\") != \"\"\n }\n # Apply those filters\n query = Sdctest.query\n for column, value in filters.items():\n query = query.filter(getattr(Sdctest,column).ilike(f'%{value}%'))\n result = query.all()\n # renders the template\n return render_template('index.html', options=options, query=query, result=result, axleopts=axleopts)\n\n else:\n return render_template('index.html', options=options)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"22640860","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n\n\ndef download_imagenet():\n ds = tfds.load('imagenet2012',\n data_dir='~/data/tf-imagenet-dirs/data',\n split='validation',\n shuffle_files=False,\n download=False,\n as_supervised=True)\n return ds\n\n\ndef resize_with_crop(image, preprocessor, need_transpose):\n from tensorflow.python.keras.applications import imagenet_utils\n image = tf.cast(image, tf.float32)\n image = tf.image.resize(image, (256, 256))\n image = tf.image.central_crop(image, 0.875) # 224x224\n if need_transpose:\n image = image[..., ::-1]\n if type(preprocessor) == str:\n image = imagenet_utils.preprocess_input(image, mode=preprocessor)\n elif preprocessor is not None:\n image = preprocessor(image)\n return image\n\n\ndef quantize_model_with_imagenet(keras_model, preprocessor, need_transpose, max_i=500):\n def representative_dataset():\n ds = download_imagenet()\n for i, (image, label) in enumerate(ds):\n if i==max_i:\n break\n image = resize_with_crop(image, preprocessor, need_transpose)\n image = tf.reshape(image, (1, *image.shape))\n yield [image]\n\n converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n converter.representative_dataset = representative_dataset\n converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n tflite_model = converter.convert()\n return tflite_model\n\n\ndef main():\n keras_model = tf.keras.applications.ResNet50(weights='imagenet')\n keras_model.summary()\n preprocessor = 'caffe'\n need_transpose = False\n tflite_model_buf = quantize_model_with_imagenet(keras_model, preprocessor, need_transpose)\n\n\nif __name__=='__main__':\n main()\n","sub_path":"closed/Edgecortix/calibrate_tensorflow_model.py","file_name":"calibrate_tensorflow_model.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"359631443","text":"#!/usr/bin/env python2\n\"\"\"2015/Jul/5 @ Zdenek Styblik \nDesc: Fetch RSS and pipe it into IRC bot.\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport pickle\nimport signal\nimport sys\nimport time\nimport traceback\n\nimport feedparser\nimport requests\n\nEXPIRATION = 86400 # seconds\nHTTP_TIMEOUT = 30 # seconds\n\n\ndef format_message(url, msg_attrs, handle=None):\n \"\"\"Return pre-formatted message.\n\n :type url: str\n :type msg_attrs: tuple\n :type handle: str\n \"\"\"\n if handle:\n if msg_attrs[1]:\n tag = '%s-%s' % (handle, msg_attrs[1])\n else:\n tag = '%s' % handle\n\n msg = '[%s] %s | %s\\n' % (tag, msg_attrs[0], url)\n else:\n msg = '%s\\n' % url\n\n return msg\n\n\ndef get_rss(logger, url, timeout):\n \"\"\"Fetch contents of given URL.\n\n :type logger: `logging.Logger`\n :type url: str\n :type timeout: int\n\n :rtype: str\n \"\"\"\n try:\n rsp = requests.get(url, timeout=timeout)\n rsp.raise_for_status()\n data = rsp.text\n del rsp\n logger.debug('Got RSS data.')\n except Exception:\n logger.debug('Failed to get RSS data.')\n logger.debug(traceback.format_exc())\n data = None\n\n return data\n\n\ndef main():\n \"\"\"Main.\"\"\"\n logging.basicConfig(stream=sys.stdout)\n logger = logging.getLogger('rss2irc')\n args = parse_args()\n if args.verbosity:\n logger.setLevel(logging.DEBUG)\n\n if args.cache_expiration < 0:\n logger.error(\"Cache expiration can't be less than 0.\")\n sys.exit(1)\n\n if not os.path.exists(args.output):\n logger.error(\"Ouput '%s' doesn't exist.\", args.output)\n sys.exit(1)\n\n news = {}\n for rss_url in args.rss_urls:\n data = get_rss(logger, rss_url, args.rss_http_timeout)\n if not data:\n logger.error('Failed to get RSS from %s', rss_url)\n sys.exit(1)\n\n parse_news(data, news)\n\n if not news:\n logger.info('No news?')\n sys.exit(0)\n\n cache = read_cache(logger, args.cache)\n scrub_cache(logger, cache)\n\n for key in news.keys():\n if key in cache:\n logger.debug('Key %s found in cache', key)\n cache[key] = int(time.time()) + args.cache_expiration\n news.pop(key)\n\n if not args.cache_init:\n write_data(logger, news, args.output, args.handle, args.sleep)\n\n expiration = int(time.time()) + args.cache_expiration\n for key in news.keys():\n cache[key] = expiration\n\n write_cache(cache, args.cache)\n\n\ndef parse_args():\n \"\"\"Return parsed CLI args.\n\n :rtype: `argparse.Namespace`\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--verbose',\n dest='verbosity', action='store_true', default=False,\n help='Increase logging verbosity.')\n parser.add_argument('--rss-url',\n dest='rss_urls', action='append', required=True,\n help='URL of RSS Feed.')\n parser.add_argument('--rss-http-timeout',\n dest='rss_http_timeout', type=int,\n default=HTTP_TIMEOUT,\n help=('HTTP Timeout. Defaults to %i seconds.'\n % HTTP_TIMEOUT))\n parser.add_argument('--handle',\n dest='handle', type=str, default=None,\n help='IRC handle of this feed.')\n parser.add_argument('--output',\n dest='output', type=str, required=True,\n help='Where to output formatted news.')\n parser.add_argument('--cache',\n dest='cache', type=str, default=None,\n help='Path to cache file.')\n parser.add_argument('--cache-expiration',\n dest='cache_expiration', type=int, default=EXPIRATION,\n help='Time, in seconds, for how long to keep items '\n 'in cache.')\n parser.add_argument('--cache-init',\n dest='cache_init', action='store_true', default=False,\n help='Prevents posting news to IRC. This is useful '\n 'when bootstrapping new RSS feed.')\n parser.add_argument('--sleep',\n dest='sleep', type=int, default=2,\n help='Sleep between messages in order to avoid '\n 'Excess Flood at IRC.')\n return parser.parse_args()\n\n\ndef parse_news(data, news):\n \"\"\"Parse-out link and title out of XML.\"\"\"\n if not isinstance(news, dict):\n raise ValueError\n\n feed = feedparser.parse(data)\n for entry in feed['entries']:\n link = entry.pop('link', None)\n title = entry.pop('title', None)\n if not 'link' and not 'title':\n continue\n\n category = entry.pop('category', None)\n news[link] = (title, category)\n\n\ndef read_cache(logger, cache_file):\n \"\"\"Read file with Py pickle in it.\n\n :type logger: `logging.Logger`\n :type cache_file: str\n\n :rtype: dict\n \"\"\"\n if not cache_file:\n return {}\n elif not os.path.exists(cache_file):\n logger.warn(\"Cache file '%s' doesn't exist.\", cache_file)\n return {}\n\n with open(cache_file, 'r') as fhandle:\n cache = pickle.load(fhandle)\n\n logger.debug(cache)\n return cache\n\n\ndef scrub_cache(logger, cache):\n \"\"\"Scrub cache and remove expired items.\n\n :type logger: `logging.Logger`\n :type cache: dict\n \"\"\"\n time_now = time.time()\n for key in cache.keys():\n try:\n expiration = int(cache[key])\n except ValueError:\n logger.error(traceback.format_exc())\n logger.error(\"Invalid cache entry will be removed: '%s'\",\n cache[key])\n cache.pop(key)\n continue\n\n if expiration < time_now:\n logger.debug('URL %s has expired.', key)\n cache.pop(key)\n\n\ndef signal_handler(signum, frame):\n \"\"\"Handle SIGALRM signal.\"\"\"\n raise ValueError\n\n\ndef write_cache(data, cache_file):\n \"\"\"Dump data into file as a pickle.\n\n :type data: dict\n :type cache_file: str\n \"\"\"\n if not cache_file:\n return\n\n with open(cache_file, 'w') as fhandle:\n pickle.dump(data, fhandle, pickle.HIGHEST_PROTOCOL)\n\n\ndef write_data(logger, data, output, handle=None, sleep=2):\n \"\"\"Write data into file.\n\n :type logger: `logging.Logger`\n :type data: dict\n :type output: str\n :type handle: str\n :type sleep: int\n \"\"\"\n with open(output, 'a') as fhandle:\n for url in data.keys():\n msg = format_message(url, data[url], handle)\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(5)\n try:\n logger.debug('Will write %s', repr(msg))\n fhandle.write(msg.encode('utf-8'))\n signal.alarm(0)\n time.sleep(sleep)\n except ValueError:\n logger.debug(traceback.format_exc())\n logger.debug('Failed to write %s, %s', url, data[url])\n data.pop(url)\n\n signal.alarm(0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rss2irc.py","file_name":"rss2irc.py","file_ext":"py","file_size_in_byte":7232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"482712160","text":"#loop 1 = 100 is divibe by 4d\n\nclass Divisible:\n n = 0\n for x in range(101):\n if x % 4 == 0:\n print(x)\n \n# use while loop to perform the same action\n\n'''a = 0\nwhile a <= 100:\n\n \n a += 1\n if a % 4 == 0:\n print(a)'''","sub_path":"forLoop2.py","file_name":"forLoop2.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"101784357","text":"from Helper import read_input\n\ninput = read_input('InputDay18.txt')\n\n\nclass Token:\n KIND_NUMBER = 1\n KIND_PAREN_OPEN = 2\n KIND_PAREN_CLOSE = 3\n KIND_MULT = 4\n KIND_ADD = 5\n\n def __init__(self, kind, value=None):\n self.kind = kind\n self.value = value\n\n\ndef parse_number(expr):\n result = ''\n i = 0\n while i < len(expr) and expr[i].isdigit():\n result = result + expr[i]\n i += 1\n\n return int(result), i\n\n\ndef tokenize(expr):\n index = 0\n tokens = []\n paren_count = 0\n while index < len(expr):\n if expr[index].isdigit():\n number, advance = parse_number(expr[index:])\n index += advance\n tokens.append(Token(Token.KIND_NUMBER, number))\n continue\n elif expr[index] == '(':\n paren_count += 1\n tokens.append(Token(Token.KIND_PAREN_OPEN))\n elif expr[index] == ')':\n if paren_count == 0:\n raise Exception('Unmatched parenthesis; found excess at index {}'.format(index))\n paren_count -= 1\n tokens.append(Token(Token.KIND_PAREN_CLOSE))\n elif expr[index] == '*':\n tokens.append(Token(Token.KIND_MULT))\n elif expr[index] == '+':\n tokens.append(Token(Token.KIND_ADD))\n index += 1\n if paren_count > 0:\n raise Exception('Unmatched opening parenthesis.')\n return tokens\n\n\nclass Node:\n def __init__(self):\n self.nodes = []\n\n\ndef parse_op(tokens, index=0):\n node = Node()\n while index < len(tokens):\n if tokens[index].kind == Token.KIND_PAREN_OPEN:\n sub_node, new_index = parse_op(tokens, index + 1)\n node.nodes.append(sub_node.nodes)\n index = new_index\n continue\n elif tokens[index].kind == Token.KIND_PAREN_CLOSE:\n return node, index + 1\n elif tokens[index].kind == Token.KIND_NUMBER:\n node.nodes.append(tokens[index].value)\n elif tokens[index].kind == Token.KIND_MULT:\n node.nodes.append('*')\n elif tokens[index].kind == Token.KIND_ADD:\n node.nodes.append('+')\n index += 1\n return node, index\n\n\ndef parse(tokens):\n parsed, _ = parse_op(tokens)\n return parsed.nodes\n\n\ndef evaluate_expression(expr):\n result = None\n last_op = None\n index = 0\n while index < len(expr):\n if not result:\n result = evaluate_expression(expr[index]) \\\n if isinstance(expr[index], list) else expr[index]\n elif expr[index] == '+' or expr[index] == '*':\n last_op = expr[index]\n elif isinstance(expr[index], list):\n if last_op == '+':\n result += evaluate_expression(expr[index])\n elif last_op == '*':\n result *= evaluate_expression(expr[index])\n else:\n if last_op == '+':\n result += expr[index]\n elif last_op == '*':\n result *= expr[index]\n index += 1\n return result\n\n\ndef evaluate_language(expr):\n tokens = tokenize(expr)\n parsed = parse(tokens)\n return evaluate_expression(parsed)\n\n\nsum = 0\nfor line in input:\n result = evaluate_language(line)\n sum += result\nprint(sum)\n","sub_path":"Day18a.py","file_name":"Day18a.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"505262374","text":"import pandas as pd\ntourney_list = pd.read_csv('../../data/01_raw/tournament_year.csv', sep=\"|\")\n\n# Fix data\nname_replace='https://bwfworldtour.bwfbadminton.com/tournament/3317/hsbc-bwf-world-tour-finals-2018/'\ntourney_list['t_web_link'][928] = name_replace\n\ntourney_id_list=[]\nfor step in range(0,len(tourney_list)):\n t_url=tourney_list['t_web_link'][step]\n if t_url != 'none':\n url_split = t_url.split('/')\n tourney_id = url_split[4] \n else:\n tourney_id = ''\n t_id={\n 't_id': tourney_id} \n tourney_id_list.append(t_id)\n \nt_id_df=pd.DataFrame(tourney_id_list) \n\ntourney_list = tourney_list.assign(t_id_df=t_id_df.values)\ntourney_list = tourney_list.rename(columns={'t_id_df':'t_id'})\nfilename = \"../../data/02_intermediate/tourney_list.csv\"\ntourney_list.to_csv(filename, index=False, sep='|', header=True)","sub_path":"munge/02_intermediate/01_tourney_list.py","file_name":"01_tourney_list.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"84724591","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/gmisclib/g_lpc.py\n# Compiled at: 2010-04-21 17:33:30\n\"\"\"Linear prediction of signals\"\"\"\nimport numpy, lapack_dgesv\n\ndef lp1_fit(y, x, indices, noise=0.0):\n \"\"\"Predicts y[i] in terms of the set of x[i+q] for q in indices.\"\"\"\n y = numpy.asarray(y, numpy.float)\n x = numpy.asarray(x, numpy.float)\n m = x.shape[0]\n assert x.shape == (m,)\n assert y.shape == (m,)\n idx = indices[:]\n idx.sort()\n nix = len(idx)\n imin = idx[0]\n imax = idx[(-1)]\n noise2 = noise * noise\n n = len(indices)\n phi = numpy.zeros((n, n), numpy.double)\n phistar = numpy.zeros((n, 1), numpy.double)\n s = max(-imin, 0)\n e = min(m - imax - 1, m - 1)\n mm = e - s + 1\n fmm = float(mm)\n for i in range(nix):\n ii = idx[i]\n for j in range(nix):\n jj = idx[j]\n phi[(i, j)] = numpy.dot(x[s + ii:s + ii + mm], x[s + jj:s + jj + mm]) / fmm\n\n phi[(i, i)] += noise2\n phistar[(i, 0)] += numpy.dot(y[s:s + mm], x[s + ii:s + ii + mm]) / fmm\n\n coef = lapack_dgesv.dgesv(phi, phistar)\n return (coef[:, 0], idx)\n\n\ndef add_sloppy(a, b, offset):\n \"\"\"Accumulate b onto a.\n Allow b to be smaller (fill with zeros), or larger (drop).\"\"\"\n n = a.shape[0]\n m = b.shape[0]\n if offset < 0:\n b0 = -offset\n a0 = 0\n else:\n b0 = 0\n a0 = offset\n ae = n\n be = m\n if ae - a0 > be - b0:\n ae = a0 + (be - b0)\n if be - b0 > ae - a0:\n be = b0 + (ae - a0)\n numpy.add(a[a0:ae], b[b0:be], a[a0:ae])\n\n\ndef lp1_run(x, coef, indices):\n idx = indices[:]\n idx.sort()\n x = numpy.asarray(x, numpy.double)\n n = x.shape[0]\n o = numpy.zeros((n,), numpy.double)\n for j in range(len(idx)):\n add_sloppy(o, x * coef[j], -idx[j])\n\n return o\n\n\nif __name__ == '__main__':\n di = [\n 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]\n d = [0, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5, 0.5, 1, 0.5,\n 0, 0.5, 1, 0.5, 0, 0, 0.5, 1, 0.5, 0, 0]\n coef, idx = lp1_fit(d, di, [-1, 0, 1], 0.0001)\n tmp = lp1_run(di, coef, idx)\n assert numpy.absolute(numpy.ravel(tmp - d)) < 0.0001\n coef, idx = lp1_fit(di[1:], di[:-1], [-1, 0, 1], 0.0001)\n tmp = lp1_run(di[:-1], coef, idx)\n assert numpy.absolute(numpy.ravel(tmp - di[1:])) < 0.0001","sub_path":"pycfiles/gmisclib-0.73.0.linux-x86_64.tar/g_lpc.py","file_name":"g_lpc.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"641804440","text":"from .WebCrawlerSettings import *\n\n#main variables\nname = \"Jet Reports\"\nurl = \"https://support.jetglobal.com/hc/en-us/articles/223125607-Jet-Reports-Release-Notes\"\n\n##################################################\n#define main settings\nfind_dllink = False\nfind_dllink_x86 = False\nfind_dllink_x64 = False\n\nfind_checksum = False\nfind_checksum_x86 = False\nfind_checksum_x64 = False\n\nchecksum_type = \"\"\n\nNew_App = False\n#################################\n\ndef crawl_data(url):\n req = Request(url=url, headers=headers)\n page_html = uReq(req).read()\n page_soup = soup(page_html, \"html.parser\")\n\n return page_soup\n\n#######################################\n\ndef crawl_version(data):\n\n r = \"Build (.*?)\"\n\n strongs = data.findAll(\"strong\")\n\n versions_list = re.findall(r, str(strongs))\n versions_list = [w.replace('
', '') for w in versions_list]\n versions_list = [w.replace('', '') for w in versions_list]\n\n return versions_list\n\n################################################################\n","sub_path":"crawlers/JetReports.py","file_name":"JetReports.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"599546767","text":"from time import sleep\nfrom selenium import webdriver\nclass Test_File:\n def setup(self):\n self.driver = webdriver.Chrome()\n self.driver.implicitly_wait(5)\n self.driver.maximize_window()\n def teardown(self):\n self.driver.quit()\n def test_file(self):\n self.driver.get('https://www.baidu.com/')\n self.driver.find_element_by_xpath('//*[@id=\"form\"]/span[1]/span[1]').click() #点击按图片搜索按钮\n ele = self.driver.find_element_by_xpath('//*[@id=\"form\"]/div/div[2]/div[2]/input') #定位到上传文件按钮\n ele.send_keys('/home/ouyi/goods02.jpg') #上传图片\n sleep(3)","sub_path":"web/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"347447346","text":"import string\nclass Level:\n '''\n Parse maps.\n '''\n def __init__(self,lines):\n GOAL = '.'\n GOAL_AND_STONE = '@'\n STONE = '$'\n BLOCK = '#'\n PLAYER = string.digits\n PLAYER_AND_GOAL = string.ascii_uppercase\n\n self.lines = lines\n self.M = len(self.lines);self.N = max([len(line) for line in lines])\n self.at_player = {}\n self.is_goal = {}\n self.at_stone = {}\n self.is_clear = {}\n self.stone_num = 1\n for i in range(1,len(self.lines)+1):\n line = lines[i-1]\n for j in range(1,len(line)+1):\n c = line[j-1]\n if c in GOAL_AND_STONE:\n self.is_goal[(i,j)] = True\n self.at_stone[(i,j)] = self.stone_num\n self.stone_num += 1\n elif c in GOAL:\n self.is_goal[(i,j)] = True\n self.is_clear[(i,j)] = True\n elif c in STONE:\n self.at_stone[(i,j)] = self.stone_num\n self.stone_num += 1\n elif c in PLAYER_AND_GOAL:\n self.is_goal[(i,j)] = True\n self.at_player[(i,j)] = int(ord(c) - ord('A'))+1\n elif c in PLAYER:\n self.at_player[(i,j)] = int(c)\n elif not c in BLOCK:\n self.is_clear[(i,j)] = True\n","sub_path":"clients/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"175565533","text":"import os\nimport shutil\n\ngetOSType = os.name\n\ndef gettingDataFromTheWindows():\n file = \"C:/Users/HP/Desktop/in\"\n file2 = \"C:/Users/HP/Desktop\"\n list = os.listdir(file)\n list2 = os.listdir(file2)\n for i in list:\n shutil.copy2(file + \"/\" + i, \"C:/Users/HP/Desktop/out\")\n\n for i in list2:\n if i.endswith(\".zip\"):\n shutil.copy2(file2 + \"/\" + i, \"C:/Users/HP/Desktop/out\")\n os.remove(file2 + \"/\" + i)\n else:\n continue\n\n\ndef copyToExternalDirection():\n file1 = \"C:/Users/HP/Desktop/out\"\n list1 = os.listdir(file1)\n\n for i in list1:\n if not os.path.exists(\"G:/NewFile\"):\n os.makedirs(\"G:/NewFile\")\n shutil.copy2(file1 + \"/\" + i, \"G:/NewFile\")\n else:\n shutil.copy2(file1 + \"/\" + i, \"G:/NewFile\")\n\nif str(getOSType) == \"posix\":\n print(\"MacOS\")\n\nelif str(getOSType) == \"nt\":\n print(\"Windows\")\n #gettingDataFromTheWindows()\n copyToExternalDirection()\n","sub_path":"SpywareTest_0.0.01.py","file_name":"SpywareTest_0.0.01.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"118115143","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\nimport datetime\nfrom openerp.exceptions import Warning\n\nSELECTION_MONTH = []\n\nfor month in range(1, 13):\n if month < 10:\n value = '0%d' % month\n else:\n value = '%d' % month\n SELECTION_MONTH.append((month, value))\n\n\nclass jj_workplan(models.Model):\n _name = 'jj_workplan.jj_workplan'\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n\n # 查表找到当前用户\n def _employee_get(self):\n resource = self.env['resource.resource'].search([('user_id', '=', self.env.user.id)])\n employee = self.env['hr.employee'].search([('resource_id', '=', resource.id)])\n return employee\n\n # 查表找到当前用户所在部门\n def _department_get(self):\n return self._employee_get().department_id\n\n # 实时计算工作计划进度条\n @api.depends('time_schedule')\n def _compute_time(self):\n if self.plan_start_date and self.plan_end_date:\n plan_start_date = datetime.datetime.strptime(self.plan_start_date, '%Y-%m-%d %H:%M:%S')\n plan_end_date = datetime.datetime.strptime(self.plan_end_date, '%Y-%m-%d %H:%M:%S')\n estimate_delta = plan_end_date - plan_start_date\n estimate_before = estimate_delta.days * 24 * 60 * 60 + estimate_delta.seconds\n if self.actual_finish_time:\n actual_finish_time = datetime.datetime.strptime(self.actual_finish_time, '%Y-%m-%d %H:%M:%S')\n actual_delta = actual_finish_time - plan_start_date\n actual_before = actual_delta.days * 24 * 60 * 60 + actual_delta.seconds\n self.time_schedule = float(actual_before) / float(estimate_before) * 100\n else:\n now_delta = datetime.datetime.now() - plan_start_date\n now_before = now_delta.days * 24 * 60 * 60 + now_delta.seconds\n self.time_schedule = float(now_before) / float(estimate_before) * 100\n\n # 判断当前用户是否是创建用户\n # 如果是 在根据状态来让能修改的地方\n def _is_employee(self):\n if self.env.user == self.employee_id.user_id:\n if self.state == 'Draft':\n self.is_employee = 'Draft'\n if self.state == 'Conduct':\n self.is_employee = 'Conduct'\n else:\n self.is_employee = 'False'\n\n name = fields.Char(string=\"事项\", required=True)\n employee_id = fields.Many2one('hr.employee', string=\"创建人\", readonly=True, default=_employee_get)\n department_id = fields.Many2one('hr.department', string=\"部门\", default=_department_get)\n plan_start_date = fields.Datetime(string=\"计划开始时间\", required=True)\n plan_end_date = fields.Datetime(string=\"计划结束时间\", required=True)\n actual_finish_time = fields.Datetime(string=\"实际完成时间\")\n description = fields.Text(string=\"描述\")\n is_employee = fields.Char(default='Draft', compute=_is_employee)\n cc = fields.Many2many('res.users', string='抄送')\n time_schedule = fields.Integer(string='所耗时间占比', compute=_compute_time)\n state = fields.Selection([('Draft', '草稿'), ('Conduct', '进行中'), ('Done', '完成')], default=\"Draft\", string='状态')\n month = fields.Selection(SELECTION_MONTH, string='月份',\n default=datetime.datetime.today().month,\n automatic=True, required=True)\n\n # 发消息\n @api.multi\n def send_followers(self, body):\n followers = [x.partner_id.id for x in self.message_follower_ids]\n self.message_post(body=body, type=\"notification\", subtype=\"mt_comment\", parnter_ids=followers)\n return True\n\n @api.model\n def create(self, vals):\n # 开始时间最多能提前5个小时\n if datetime.datetime.strptime(vals['plan_start_date'],\n '%Y-%m-%d %H:%M:%S') < datetime.datetime.now() - datetime.timedelta(\n hours=5) or datetime.datetime.strptime(vals['plan_start_date'],\n '%Y-%m-%d %H:%M:%S') > datetime.datetime.strptime(\n vals['plan_end_date'], '%Y-%m-%d %H:%M:%S'):\n raise Warning('时间不正确')\n vals['state'] = 'Conduct'\n self.send_followers(\"开始\")\n a = self.search([('id', '!=', 0)], order='id desc', limit=1)\n # 将授权用户拉入关注中\n if len(vals['cc']) > 0:\n for u in vals['cc'][0][-1]:\n res_users = self.env['res.users'].search([('id', '=', u)])\n mail = {u'partner_id': res_users.partner_id.id,\n u'res_model': 'jj_workplan.jj_workplan',\n u'res_id': a.id + 1}\n self.env['mail.followers'].sudo().create(mail)\n return super(jj_workplan, self).create(vals)\n\n @api.multi\n def write(self, vals):\n # 修改预计时间后 发消息\n if self.plan_end_date:\n if vals.get('plan_end_date', False):\n context = str(datetime.datetime.strptime(self.plan_end_date, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(\n hours=8)) + '更改为' + str(\n datetime.datetime.strptime(vals['plan_end_date'], '%Y-%m-%d %H:%M:%S') + datetime.timedelta(\n hours=8))\n self.send_followers('预计完成时间由' + context)\n # 如果新增授权用户 拉入关注中\n if 'cc' in vals.keys():\n if vals['cc'][0][-1]:\n for u in vals['cc'][0][-1]:\n res_users = self.env['res.users'].search([('id', '=', u)])\n mail = self.env['mail.followers'].search(\n [('partner_id', '=', res_users.partner_id.id), ('res_model', '=', 'jj_workplan.jj_workplan'),\n ('res_id', '=', self.id)])\n if not mail:\n mail_followers = {u'res_model': 'jj_workplan.jj_workplan',\n u'res_id': self.id,\n u'partner_id': res_users.partner_id.id\n }\n self.env['mail.followers'].sudo().create(mail_followers)\n return super(jj_workplan, self).write(vals)\n\n # @api.one\n # def submit_button(self):\n # \tself.state = 'Conduct'\n # \tself.send_followers(\"开始\")\n\n @api.one\n def done_button(self):\n if self.time_schedule > 100:\n over_time = '超时' + str(int(self.time_schedule) - 100) + '%'\n else:\n over_time = 'good,在预期内完成了任务。'\n self.actual_finish_time = datetime.datetime.now()\n self.state = 'Done'\n self.send_followers(\"完成\" + \"\\n\" + over_time)\n","sub_path":"jj_workplan/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"573244849","text":"# https://www.kaggle.com/chmaxx/quick-regression/code\n# https://www.kaggle.com/chmaxx/train-12-regressors-with-just-one-line-of-code\n\nimport numpy as np \nimport pandas as pd \n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.compose import TransformedTargetRegressor\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.pipeline import make_pipeline\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import FunctionTransformer\n\nfrom sklearn.model_selection import cross_val_score\n\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import BayesianRidge\nfrom sklearn.linear_model import SGDRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.svm import LinearSVR\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\n\nimport xgboost as xgb\nimport lightgbm as lgb\n\nimport time\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n\ndef log_transform(x):\n return np.log1p(x)\n\ndef inverse_log_transform(x):\n return np.expm1(x)\n\n\ndef get_classifiers():\n\n \"\"\"\n Provide lists of regression classifiers and their names.\n \"\"\"\n n_jobs = -1\n random_state = 1\n\n classifiers = [\n DummyRegressor(), \n LinearRegression(n_jobs=n_jobs), \n Ridge(random_state=random_state), \n Lasso(random_state=random_state), \n ElasticNet(random_state=random_state),\n KernelRidge(),\n SGDRegressor(random_state=random_state),\n SVR(kernel=\"linear\"),\n LinearSVR(random_state=1),\n DecisionTreeRegressor(random_state=random_state),\n RandomForestRegressor(n_jobs=n_jobs, random_state=random_state),\n GradientBoostingRegressor(random_state=random_state),\n lgb.LGBMRegressor(n_jobs=n_jobs, random_state=random_state),\n xgb.XGBRegressor(objective=\"reg:squarederror\", n_jobs=n_jobs, random_state=random_state),\n ]\n\n clf_names = [\n \"DummyRegressor \",\n \"LinearRegression \", \n \"Ridge \",\n \"Lasso \",\n \"ElasticNet \",\n \"KernelRidge \",\n \"SGDRegressor \",\n \"SVR \",\n \"LinearSVR \",\n \"DecisionTreeRegressor\",\n \"RandomForest \", \n \"GBMRegressor \", \n \"LGBMRegressor \", \n \"XGBoostRegressor \",\n ]\n\n return clf_names, classifiers\n\n\n\ndef prepare_data(df, target_name):\n\n \"\"\"\n Separate descriptive variables and target variable.\n Separate numerical and categorical columns.\n \"\"\"\n\n if target_name is not None:\n X = df.drop(target_name, axis=1)\n y = df[target_name]\n else:\n X = df\n y = None\n\n # get list of numerical & categorical columns in order to process these separately in the pipeline \n num_cols = X.select_dtypes(\"number\").columns\n cat_cols = X.select_dtypes(\"object\").columns\n \n return X, y, num_cols, cat_cols\n\n\ndef get_pipeline(classifier, num_cols, cat_cols, impute_strategy, log_x, log_y):\n\n \"\"\"\n Create Pipeline with a separate pipe for categorical and numerical data.\n Automatically impute missing values, scale and then one hot encode.\n \"\"\"\n\n # the numeric transformer gets the numerical data acording to num_cols\n # first step: the imputer imputes all missing values to the provided strategy argument\n # second step: all numerical data gets stanadard scaled \n if log_x == False:\n numeric_transformer = Pipeline(steps=[\n ('imputer', make_pipeline(SimpleImputer(strategy=impute_strategy))),\n ('scaler', StandardScaler())])\n # if log_x is \"True\" than log transform feature values\n else:\n numeric_transformer = Pipeline(steps=[\n ('imputer', make_pipeline(SimpleImputer(strategy=impute_strategy))),\n ('log_transform', FunctionTransformer(np.log1p)),\n ('scaler', StandardScaler()),\n ])\n \n # the categorical transformer gets all categorical data according to cat_cols\n # first step: imputing missing values\n # second step: one hot encoding all categoricals\n categorical_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='most_frequent', fill_value='missing')),\n ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n \n # the column transformer creates one Pipeline for categorical and numerical data each\n preprocessor = ColumnTransformer(\n transformers=[\n ('num', numeric_transformer, num_cols),\n ('cat', categorical_transformer, cat_cols)])\n \n # return the whole pipeline for the classifier provided in the function call\n if log_y == False:\n return Pipeline(steps=[('preprocessor', preprocessor), ('classifier', classifier)])\n # if log_y is \"True\" than use a TransformedTargetRegressor with log and inverse log functions for \"y\"\n else:\n transformed_classifier = TransformedTargetRegressor(regressor=classifier, \n func=log_transform, inverse_func=inverse_log_transform)\n return Pipeline(steps=[('preprocessor', preprocessor), ('classifier', transformed_classifier)])\n\n\ndef score_models(df, target_name, sample_size=None, \n impute_strategy=\"mean\", scoring_metric=\"r2\", log_x=False, log_y=False, verbose=True):\n\n \"\"\"\n This function yields error scores for a large variety of common regression classifiers on provided training data. \n\n Function separates numerical and categorical data based on dtypes of the dataframe columns. Missing values are imputed. Categorical data is one hot encoded, numerical data standard scaled. All classifiers are used with default settings and crossvalidated.\n \n The function returns a dataframe with error scores of all classifiers as well as the mean of all results in the last row of the dataframe.\n\n Parameters\n ----------\n df : Pandas dataframe \n Pandas dataframe with your training data\n target_name : str\n Column name of target variable\n sample_size : int, default \"None\" (score on all available samples)\n Number of samples for scoring the model\n impute_strategy : str, default \"mean\" \n Strategy for SimpleImputer, can be \"mean\" (default), \"median\", \"most_frequent\" or \"constant\"\n scoring_metric : str, default \"r2\"\n scoring metric for regressor: \"r2\" (default), \"explained_variance\", \"max_error\", \n \"neg_mean_absolute_error\", \"neg_mean_squared_error\", \"neg_mean_squared_log_error\", \"neg_median_absolute_error\"\n log_x : bool, default \"False\" \n Log transform features variable(s)\n log_y : bool, default \"False\" \n Log transform target variable\n verbose : bool, default \"True\" \n Print results during crossvalidation\n \n Returns\n -------\n DataFrame\n 1st column : Name of classifier\n 2nd column : scoring result\n\n Example\n -------\n X, y = sklearn.datasets.make_regression()\n X, X_test, y, _ = train_test_split(X, y)\n\n df = pd.DataFrame(X)\n df[\"target_variable\"] = y\n df_test = pd.DataFrame(X_test)\n\n scores_dummy = score_models(df, \"target_variable\")\n display(scores_dummy)\n \n # further use: train and predict\n pipelines = train_models(df, \"target_variable\")\n predictions = predict_from_models(df_test, pipelines)\n predictions.head()\n\n \"\"\"\n\n \n if sample_size is not None:\n df = df.sample(sample_size)\n \n # retrieve X, y and separated columns names for numerical and categorical data\n X, y, num_cols, cat_cols = prepare_data(df, target_name)\n\n scores = []\n\n clf_names, classifiers = get_classifiers()\n if verbose == True:\n print(f\"Classifier Metric ({scoring_metric})\")\n print(\"-\"*30)\n for clf_name, classifier in zip(clf_names, classifiers):\n start_time = time.time()\n \n # create a pipeline for each classifier\n clf = get_pipeline(classifier, num_cols, cat_cols, impute_strategy, log_x, log_y)\n \n # crossvalidate classifiers on training data\n cv_score = cross_val_score(clf, X, y, cv=3, scoring=scoring_metric)\n \n if verbose == True:\n print(f\"{clf_name} {cv_score.mean(): .4f} | {(time.time() - start_time):.2f} secs\")\n \n scores.append([clf_name.strip(), cv_score.mean()])\n\n scores = pd.DataFrame(scores, columns=[\"Classifier\", scoring_metric]).sort_values(scoring_metric, ascending=False)\n \n # just for good measure: add the mean of all scores to dataframe\n scores.loc[len(scores) + 1, :] = [\"mean_all\", scores[scoring_metric].mean()]\n\n return scores.reset_index(drop=True)\n \n\n\ndef train_models(df, target_name, \n impute_strategy=\"mean\", log_x=False, log_y=False, verbose=True): \n\n \"\"\"\n This function trains a large variety of common regression classifiers on provided training data. It separates numerical and categorical data based on dtypes of the dataframe columns. Missing values are imputed. Categorical data is one hot encoded, numerical data standard scaled. Each classifier is then trained with default settings.\n \n The function returns a list of fitted scikit-learn Pipelines.\n\n Parameters\n ----------\n df : Pandas dataframe \n Pandas dataframe with your training data\n target_name : str\n Column name of target variable\n sample_size : int, default \"None\" (score on all available samples)\n Number of samples for scoring the model\n impute_strategy : str, default \"mean\" \n Strategy for SimpleImputer, can be \"mean\" (default), \"median\", \"most_frequent\" or \"constant\"\n log_x : bool, default \"False\" \n Log transform features variable(s)\n log_y : bool, default \"False\" \n Log transform target variable\n verbose : bool, default \"True\" \n Print results during crossvalidation\n \n Returns\n -------\n List of fitted scikit-learn Pipelines\n\n Example:\n X, y = sklearn.datasets.make_regression()\n X, X_test, y, _ = train_test_split(X, y)\n\n df = pd.DataFrame(X)\n df[\"target_variable\"] = y\n df_test = pd.DataFrame(X_test)\n\n scores_dummy = score_models(df, \"target_variable\")\n display(scores_dummy)\n \n pipelines = train_models(df, \"target_variable\")\n\n # further use: predict from pipelines\n predictions = predict_from_models(df_test, pipelines)\n predictions.head()\n \n \"\"\"\n\n X, y, num_cols, cat_cols = prepare_data(df, target_name)\n\n pipelines = []\n\n if verbose == True:\n print(f\"Classifier Training time\")\n print(\"-\"*35)\n \n clf_names, classifiers = get_classifiers()\n for clf_name, classifier in zip(clf_names, classifiers):\n start_time = time.time()\n clf = get_pipeline(classifier, num_cols, cat_cols, impute_strategy, log_x, log_y)\n clf.fit(X, y)\n if verbose == True:\n print(f\"{clf_name} {(time.time() - start_time):.2f} secs\")\n pipelines.append(clf)\n \n return pipelines\n\n\n\ndef predict_from_models(df_test, pipelines):\n\n \"\"\"\n This function makes predictions with a list of pipelines. Test data is treated in the same pipeline the classifiers were trained on. \n \n The function returns a dataframe with all predictions ordered columnwise. Each column is named with the respective classifiers.\n\n Parameters\n ----------\n df_test : Pandas dataframe \n Dataframe with test data\n pipelines: array\n List of scikit-learn pipelines (preferably from train_models())\n\n Returns\n -------\n Pandas dataframe with prediction from each classifier, ordered columnwise. \n 1 column = results of 1 classifier.\n \n Example:\n X, y = sklearn.datasets.make_regression()\n X, X_test, y, _ = train_test_split(X, y)\n\n df = pd.DataFrame(X)\n df[\"target_variable\"] = y\n df_test = pd.DataFrame(X_test)\n\n scores_dummy = score_models(df, \"target_variable\")\n display(scores_dummy)\n \n pipelines = train_models(df, \"target_variable\")\n\n # further use: predict from pipelines\n predictions = predict_from_models(df_test, pipelines)\n predictions.head()\n \n \"\"\"\n \n X_test, _ , _, _ = prepare_data(df_test, None)\n predictions = []\n \n for pipeline in pipelines:\n preds = pipeline.predict(X_test)\n predictions.append(preds)\n \n df_predictions = pd.DataFrame(predictions).T\n clf_names, _ = get_classifiers()\n df_predictions.columns = [clf_name.strip() for clf_name in clf_names]\n\n return df_predictions\n","sub_path":"Scripts/quick_regression/quick_regression.py","file_name":"quick_regression.py","file_ext":"py","file_size_in_byte":13338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"232733970","text":"import json\nimport logging\nfrom datetime import datetime, timezone\n\nimport requests\n\nfrom config import config\n\nlogger = logging.getLogger()\n\n\ndef _get_mac():\n\ttry:\n\t\ttry:\n\t\t\tmac = open(\"/sys/class/net/ppp0/address\").read()\n\t\texcept:\n\t\t\tmac = open(\"/sys/class/net/eth0/address\").read()\n\texcept:\n\t\tmac = \"00:00:00:00:00:00\"\n\treturn mac[0:17]\n\n\ndef send_data(sensor_id, timestamp, value):\n\t\"\"\"\n\tSends data was read from sensor to M4M server\n\n\t:type sensor_id int\n\t:param sensor_id: sensor id\n\t:type timestamp: datetime.datetime or str\n\t:type value: dict\n\t:param value: Value to send\n\t\"\"\"\n\n\tif not isinstance(timestamp, str):\n\t\tif isinstance(timestamp, datetime):\n\t\t\ttimestamp = timestamp.replace(tzinfo=timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S\")\n\t\telse:\n\t\t\traise Exception(\"timestamp argument must be string or datetime\")\n\n\tdata = {\n\t\t'controller_mac': _get_mac(),\n\t\t'sensor_id': int(sensor_id),\n\t\t'value': json.dumps(value),\n\t\t'hash': \"some_hash\",\n\t\t'timestamp': timestamp,\n\t}\n\tresponse = requests.post('{}/sensor.addRecord'.format(config['m4m_server']['receiver_uri']), json=data)\n\tif response.status_code != 200:\n\t\tlogger.error(\n\t\t\t\"Failed to send data %s to the M4M server. Status code: %s. Response: \",\n\t\t\ttimestamp,\n\t\t\tresponse.status_code,\n\t\t\tresponse.text,\n\t\t)\n\t\traise Exception(\"Failed to send data to the M4M server\")\n\tlogger.info(\"Data %s was send to the M4M server\", timestamp)\n","sub_path":"m4m_client/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"453519508","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClean up Titanic files\n\"\"\"\n\nimport pandas as pd\n\ndef process_file(infilename, outfilename,\n add_survival=False):\n # Open up the csv file in to a Python object\n df = pd.read_csv(infilename, header=0)\n df.info()\n \n if add_survival:\n names = map(lambda name: name.replace('\"', ''), df_all.name)\n survived_dict = dict(zip(names, df_all.survived))\n cols = ['Survived'] + list(df.keys())\n df['Survived'] = df['Name'].map(lambda name: survived_dict[name.replace('\"', '')])\n df = df.reindex(columns=cols)\n \n # Remap sex to binary value\n df['Sex'] = df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)\n \n # Remap embarked to integer value\n df = df[df['Embarked'].notnull()]\n df['Embarked'] = df['Embarked'].map( {'C': 0, 'Q': 1, 'S': 2} ).astype(int)\n \n # Drop features\n df = df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1)\n \n # Filter missing values\n #for key in df.keys():\n # df = df[df[key].notnull()]\n df = df.dropna()\n df.info()\n \n # Write out to file\n df.to_csv(outfilename, index=False)\n\ndf_all = pd.read_excel('../titanic_data/titanic3.xls', header=0)\n\nprocess_file('../titanic_data/kaggle/train.csv', '../data/titanic_train.csv')\nprocess_file('../titanic_data/kaggle/test.csv', '../data/titanic_test.csv')\nprocess_file('../titanic_data/kaggle/test.csv', '../data/titanic_test.answers.csv', add_survival=True)","sub_path":"CS158/Projects/ps2/ps2/source/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"434787404","text":"import numpy as np\nimport statistics\nimport math\nimport torch\nimport pandas as pd\nfrom torch.utils.data import DataLoader\nfrom DataLoading import *\nfrom Preprocessing import *\nfrom SiameseNetwork import *\n\n#trial = 3 # trial 0-3\n#kid = 24 # kids from 0-44\n#move = 0 # moves from 0-17 or 0-13\n#seq = 1 #Sequence 1 or 3\n\nmask_testGold = np.load('../../dance_results/mask_testGold.npy')\n#mask_testChild = np.load('../../dance_results/mask_testChild.npy')\n#mask_trainChild = np.load('../../dance_results/mask_trainChild.npy')\nmask_trainGold = np.load('../../dance_results/mask_trainGold.npy')\ntestChild = np.load('../../dance_results/padded_testChild.npy')\ntestGold = np.load('../../dance_results/padded_testGold.npy')\ntrainChild = np.load('../../dance_results/padded_trainChild.npy')\ntrainGold = np.load('../../dance_results/padded_trainGold.npy')\ntrainScores = np.load('../../dance_results/trainScores.npy')\ntestScores = np.load('../../dance_results/testScores.npy')\n\n#revtestChild = np.flip(testChild, 1)\n#newtestChild = np.concatenate((testChild, revtestChild))\n\n#revtestGold = np.flip(testGold, 1)\n#newtestGold = np.concatenate((testGold, revtestGold))\n\n#revtrainChild = np.flip(trainChild, 1)\n#newtrainChild = np.concatenate((trainChild, revtrainChild))\n\n#revtrainGold = np.flip(trainGold, 1)\n#newtrainGold = np.concatenate((trainGold, revtrainGold))\n\n#revmask_trainGold = np.flip(mask_trainGold, 1)\n#newtrainGold = np.concatenate((mask_trainGold, revmask_trainGold))\n\n#revmask_testGold = np.flip(mask_testGold, 1)\n#newtestGold = np.concatenate((mask_testGold, revmask_testGold))\n\n#revtestScores = np.flip(testScores, 0)\n#revtrainScores = np.flip(trainScores, 0)\n#newtestScores = np.concatenate((testScores, revtestScores))\n#newtrainScores = np.concatenate((trainScores, revtrainScores))\n\n\n#train_data = myDataset(newtrainChild, newtrainGold, newmask_trainGold, newtrainScores)\n#test_data = myDataset(newtestChild, newtestGold, newmask_testGold, newtestScores)\n\ntrain_data = myDataset(trainChild, trainGold, mask_trainGold, trainScores)\ntest_data = myDataset(testChild, testGold, mask_testGold, testScores)\n\n###################\n# Hyper Parameters#\n###################\nbatch_size = 25\nhidden_size = 64\nlr_rate = .001\n\n# train and testing parameters for batching\ntrain_params = {'batch_size': batch_size,\n\t\t'shuffle': True,\n\t\t'num_workers': 0}\ntest_params = {'batch_size': batch_size,\n\t\t'shuffle': False,\n\t\t'num_workers': 0}\n\n#batch generators\ntrain_gen = DataLoader(train_data, **train_params)\ntest_gen = DataLoader(test_data, **test_params)\n\nhyper_params = {'input_size': 60,\n\t\t'hidden_size': hidden_size,\n\t\t'batch_size': batch_size}\n\n#device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n#intializing my model of Siamese NN\nmymodel = mySiameseNetwork(**hyper_params)\nmymodel = mymodel.to(device)\n\n# defining metric loss and optimizer\ncriterion = myContrastiveLoss()\n#criterion = myBasicLoss()\noptimizer = torch.optim.Adam(mymodel.parameters(), lr=lr_rate)\n\nnum_epochs = 50\n\n#saving intermediate infromation\nlosses = []\ntrain_accuracies = []\ntest_accuracies = []\n\nfor i in range(num_epochs):\n\tmymodel.train(True)\n\tfor child, gold, weights, scores in train_gen:\n\t\tchild = child.to(device)\n\t\tgold = gold.to(device)\n\t\tscores = scores.to(device)\n\t\t#clearing gradients\n\t\toptimizer.zero_grad()\n\t\t#forward pass\n\t\toutput1, output2= mymodel(child, gold)\n\t\toutput1 = torch.stack([output1[j, w-1, :] for j, w in enumerate(weights)])\n\t\toutput2 = torch.stack([output2[j, w-1, :] for j, w in enumerate(weights)])\n\t\t# Use the weight matrix\n\t\tloss, y_pred = criterion(output1, output2, scores)\n\t\tacc = newaccuracy(y_pred, scores)\n\t\tloss.backward()\n\t\toptimizer.step()\n\tprint(y_pred.t(), scores)\t\n\tmymodel.train(False)\n\tfor child, gold, weights, scores in train_gen:\n\t\tchild = child.to(device)\n\t\tgold = gold.to(device)\n\t\tscores = scores.to(device)\n\t\toutput1, output2 = mymodel(child, gold)\n\t\toutput1 = torch.stack([output1[j, w-1, :] for j, w in enumerate(weights)])\n\t\toutput2 = torch.stack([output2[j, w-1, :] for j, w in enumerate(weights)])\n\t\tloss, y_pred = criterion(output1, output2, scores)\n\t\ttest_acc = newaccuracy(y_pred, scores)\n\n\tprint(\"Epoch number {}\\n Current loss {}\\n Current accuracy {}\\n Test accuracy {}\".format(i+1, loss.item(), acc, test_acc))\n\ttrain_accuracies.append(acc)\n\tlosses.append(loss.item())\n\ttest_accuracies.append(test_acc)\ntest = 1\nnp.save('../../dance_results/losses{}'.format(test), losses)\t\nnp.save('../../dance_results/acc{}'.format(test), train_accuracies)\nnp.save('../../dance_results/testacc{}'.format(test), test_accuracies)\ntorch.save(mymodel.state_dict(), 'noAugmentDataSNN{}'.format(test))\n","sub_path":"Dance_Imitation/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"273081635","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n\nimport time\nimport pandas as pd\nimport operator\nimport subprocess\nimport sys\n\ndef install(package):\n #install a module \n #Reference https://www.activestate.com/resources/quick-reads/how-to-install-python-packages-using-a-script/\n\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package]) \n\ntry:\n # try to import fuzzywuzzy\n from fuzzywuzzy import fuzz\n \nexcept ModuleNotFoundError:\n #if not installed then install \n install('fuzzywuzzy')\n from fuzzywuzzy import fuzz\n \n \nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\n#List of data (City, month and WeekName)\nlist_city=['chicago', 'new york city', 'washington']\nlist_month=['january', 'february', 'march', 'april', 'may', 'june','all']\nlist_week_name=['sunday','monday','tuesday','wednesday','thursday','friday','saturday','all'] \n\n\ndef choice(prompt, choices=('yes', 'no')):\n \"\"\"Return a valid input from the user given an array of possible answers.\n \n Args:\n (str)prompt - prompt with input request\n (tup)choices - tuple with elements of possibles answers\n \"\"\"\n\n while True:\n choice = input(prompt).lower()\n if choice in choices:\n break\n prompt = (\"\\nInvalid Response.Please choise again!\\n\")\n return choice\n\n\ndef similarity(input_data,data_list):\n #This function checks the similarity ratio between the input and our data list\n #Reference https://towardsdatascience.com/fuzzy-string-matching-in-python-68f240d910fe\n input_data=input_data.lower()\n ratio={}\n \n #ratio calculation \n for i in data_list:\n r=fuzz.ratio(input_data,i.lower())\n ratio[i]=r\n most_r=max(ratio.items(),key=operator.itemgetter(1))[0]\n \n if ratio[most_r] == 100:\n return (input_data,most_r,'exact')\n elif ratio[most_r] < 50:\n return (input_data,most_r,'no found')\n else:\n return (input_data,most_r,'similar')\n\n\ndef check(data): \n if data[2]=='exact':\n return data[1]\n elif data[2]=='similar':\n i=choice('Do you mean \\'{}\\' ? Enter yes or no\\n'.format(data[1].title()))\n if i=='yes':\n return data[1]\n else:\n print('\\nInvalid Response.Please choise again!\\n ')\n else:\n print('\\nInvalid Response.Please choise again!\\n ')\n return None \n\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('\\nHello!Let\\'s explore some US bikeshare data!\\n')\n city=None\n month=None\n day=None\n while True:\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n while city == None:\n city=input('Please enter a city (chicago, new york city, washington):')\n city_sim=similarity(city,list_city)\n city=check(city_sim)\n\n # get user input for month (all, january, february, ... , june)\n while month==None:\n month=input('\\nwhich month?(january,february,march,april or all(for all months)): ')\n month_sim=similarity(month,list_month)\n month=check(month_sim)\n # get user input for day of week (all, monday, tuesday, ... sunday)\n while day==None:\n day=input('\\nwhich day?(monday, tuesday, wednesday, thursday, friday, saturday, sunday or all(for all days)): ')\n day_sim=similarity(day,list_week_name)\n day=check(day_sim) \n # confirm the user input\n confirm = choice(\"\\nPlease confirm that you would like to apply \"\n \"the following filter to the bikeshare data.\"\n \"\\n\\n City: {}\\n Month: {}\\n Weekday\"\n \": {}\\n\\nEnter yes or no.\\n>\"\n .format(city, month, day ))\n if confirm.lower() == 'yes':\n break\n else:\n city=None\n month=None\n day=None\n print(\"\\nLet's try this again!\")\n print('-'*40)\n return city,month,day \n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df=pd.read_csv(CITY_DATA[city])\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['Month'] = df['Start Time'].dt.month\n df['Week_day']=df['Start Time'].dt.day_name()\n \n # filter by day of week if applicable\n if day!='all':\n # filter by day of week to create the new dataframe\n df=df[df['Week_day']==day.title()]\n \n # filter by month if applicable\n if month!='all':\n # use the index of the months list to get the corresponding int\n month = list_month.index(month) + 1\n # filter by month to create the new dataframe\n df=df[df['Month']==month]\n \n return df\n\n\ndef time_stats(df,day,month):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n if month=='all':\n #if month is given then we don't need to display the most common month\n common_month=df['Month'].mode()[0]\n print('The Most Common Month: {}'.format(str(list_month[common_month-1].title())))\n\n # display the most common day of week\n if day=='all':\n #if day is given then we don't need to display the most common day\n common_day = df['Week_day'].mode()[0]\n print('The Most Common Day Of week: {}'.format(common_day.title()))\n\n # display the most common start hour\n common_start_hour=df['Start Time'].dt.hour.mode()[0]\n print('The Most Common Start Hour: {}'.format(common_start_hour))\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n \n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n print('Most Commonly used Start Station : {}'.format(df['Start Station'].mode()[0]))\n \n\n # display most commonly used end station\n print('Most Commonly used End Station : {}'.format(df['End Station'].mode()[0]))\n\n # display most frequent combination of start station and end station trip\n df_trip=(df['Start Station']+ ' -> ' +df['End Station'])\n print('Most Commonly Used Station in End and Start Station: {}'.format(df_trip.mode()[0]))\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n \n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n print('Total Travel Time:')\n total_travel=df['Trip Duration'].sum()\n days=int(total_travel//86400)\n hours=int((total_travel% 86400)//3600)\n minutes=int(((total_travel% 86400) % 3600)//60)\n seconds=int(((total_travel% 86400) % 3600) % 60)\n print('{} days {} hours {} minutes {} seconds , total in second= {}'.format(days,hours,minutes,seconds,total_travel))\n print('_'*40)\n \n # display mean travel time\n print('Average Travel Time:')\n mean_travel=df['Trip Duration'].mean()\n days=int(mean_travel//86400)\n hours=int((mean_travel % 86400)//3600)\n minutes=int(((mean_travel % 86400) % 3600)//60)\n seconds=int(((mean_travel % 86400) % 3600) % 60)\n print('{} days {} hours {} minutes {} seconds , Average in seconds= {}'.format(days,hours,minutes,seconds,mean_travel))\n \n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n \n \ndef user_stats(df,city):\n \n \"\"\"Displays statistics on bikeshare users.\"\"\"\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n print('Numbers of user by type :')\n print(df['User Type'].value_counts().to_string())\n print('_'*40)\n\n # Display counts of gender \n if \"Gender\" in df.columns:\n print('Numbers of user by gender :')\n print(df['Gender'].value_counts().to_string())\n print('_'*50)\n else :\n print(\"We're sorry! There is no data of user genders for {}.\"\n .format(city.title()))\n\n # Display earliest, most recent, and most common year of birth\n if \"Birth Year\" in df.columns:\n earliest=df['Birth Year'].min()\n recent=df['Birth Year'].max()\n mode=df['Birth Year'].mode()[0]\n print('The earliest year of birth: {}'.format(int(earliest)))\n print('The most common year of birth: {}'.format(int(mode)))\n print('The most recent year of birth: {}'.format(int(recent)))\n else :\n print(\"We're sorry! There is no data of birth year for {}.\"\n .format(city.title()))\n\n print(\"\\nThis took {} seconds.\".format((time.time() - start_time)))\n print('-'*40)\n\n \ndef display_data(df, ref):\n \"\"\"Display 5 line of sorted raw data each time.\"\"\"\n\n print(\"\\nYou choosed to view raw data.\")\n\n # sort data by column\n ref = 0\n sort_df = choice(\"\\nHow would you like to sort the display of data?\\n\" \n \"Press Enter to view unsorted.\\n \\n \"\n \"st: Start Time\\n et: End Time\\n \"\n \"td: Trip Duration\\n ss: Start Station\\n \"\n \"es: End Station\\n\",\n ('st', 'et', 'td', 'ss', 'es', ''))\n\n order = choice(\"\\nWould you like it to be sorted ascending or \"\n \"descending? \\n asc: Ascending\\n desc: Descending\"\n \"\\n\",\n ('asc', 'desc'))\n\n if order == 'asc':\n order = True\n elif order == 'desc':\n order = False\n\n if sort_df == 'st':\n df = df.sort_values(['Start Time'], ascending=order)\n elif sort_df == 'et':\n df = df.sort_values(['End Time'], ascending=order)\n elif sort_df == 'td':\n df = df.sort_values(['Trip Duration'], ascending=order)\n elif sort_df == 'ss':\n df = df.sort_values(['Start Station'], ascending=order)\n elif sort_df == 'es':\n df = df.sort_values(['End Station'], ascending=order)\n elif sort_df == '':\n pass\n\n # each loop displays 5 lines of raw data\n while True:\n for i in range(ref, len(df.index)):\n print(\"\\n\")\n print(df.iloc[ref:ref+5].to_string())\n print(\"\\n\")\n ref += 5\n\n if choice(\"Do you want to see more?\"\n \" Enter yes or no.\\n\") == 'yes':\n continue\n else:\n break\n break\n\n return ref\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df=load_data(city,month,day)\n ref = 0\n while True:\n select_data = choice(\"\\nWhat information would you \"\n \"like to obtain?\\n\\n ts: Time Stats\\n ss: \"\n \"Station Stats\\n tds: Trip Duration Stats\\n \"\n \"us: User Stats\\n dd: Display Data\\n \"\n \"r: Restart\\n\",\n ('ts', 'ss', 'tds', 'us', 'dd', 'r'))\n if select_data == 'ts':\n time_stats(df,day,month)\n elif select_data == 'ss':\n station_stats(df)\n elif select_data == 'tds':\n trip_duration_stats(df)\n elif select_data == 'us':\n user_stats(df, city)\n elif select_data == 'dd':\n ref = display_data(df, ref)\n elif select_data == 'r':\n break\n\n restart = choice(\"\\nWould you like to restart?Enter yes or no.\\n\")\n if restart != 'yes':\n break\n\nif __name__ == \"__main__\":\n main()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":12619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"478095347","text":"'''\nGiven a string containing digits from 2-9 inclusive,\nreturn all possible letter combinations that the number could represent.\nA mapping of digit to letters (just like on the telephone buttons) is given below.\nNote that 1 does not map to any letters.\n'''\n\n\nclass Solution:\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n match = {'1':'', '2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno',\n '7':'pqrs', '8':'tuv', '9':'wxyz'}\n res = [digits]\n n = len(digits)\n\n for i in range(n):\n new_res = []\n for s in res:\n t = s\n for j in match[s[i]]:\n t = t[:i] + j + t[i + 1:]\n new_res.append(t)\n res = new_res\n return res\n\ntest = Solution()\nprint(test.letterCombinations(''))\n\n\n","sub_path":"Letter Combinations of a Phone Number.py","file_name":"Letter Combinations of a Phone Number.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"447513373","text":"#!/usr/bin/env python3\n\n\ndef get_value_suffix(value_type):\n suffix = None\n if value_type == 'OP_INTEGER':\n suffix = \"\"\n if value_type == 'OP_DECIMAL':\n suffix = \".0\"\n\n return suffix\n\n\ndef operation_to_symbol(operation):\n symbol = None\n if operation == \"PLUS_OR_MINUS\":\n symbol = \"-\" # This is on purpose since \"+\" on floats does not return the correct type\n if operation == \"MULTIPLY\":\n symbol = \"*\"\n if operation == \"DIVIDE\":\n symbol = \"/\"\n if operation == \"COMPARE\":\n symbol = \"<\"\n\n return symbol\n\n\ndef generate_state():\n print(\"struct State {\")\n print(\" OP_INTEGER_placeholder : int64\")\n print(\" OP_DECIMAL_placeholder : float64\")\n print(\"}\\n\")\n\n\ndef generage_arithmetic_fun(row_num, data_type, operation):\n suffix = get_value_suffix(data_type)\n fun_name = \"{}{}Row{}\".format(data_type, operation, row_num)\n print(\"fun {}(execCtx: *ExecutionContext, state: *State) -> nil {{\".format(fun_name))\n print(\" @execCtxStartResourceTracker(execCtx, 3)\")\n\n step_size = 100\n\n print(\" for (var i = 0; i < {}; i = i + {}) {{\".format(row_num, step_size))\n print(\" var a = state.{}_placeholder - 1000000000{}\".format(data_type, suffix))\n for i in range(step_size):\n if operation == \"COMPARE\":\n if i != 0:\n print(\" if (a {} 5{}) {{\".format(operation_to_symbol(operation), suffix))\n print(\" a = 10{}\".format(suffix))\n print(\" } else {\")\n print(\" a = 1{}\".format(suffix))\n print(\" }\")\n else:\n print(\" a = a {} 3{}\".format(operation_to_symbol(operation), suffix))\n print(\" state.{}_placeholder = a\".format(data_type))\n print(\" }\")\n\n print(\" @execCtxEndResourceTracker(execCtx, @stringToSql(\\\"{}_{}, {}\\\"))\".format(\n data_type, operation, row_num))\n print(\"}\")\n\n print()\n\n return fun_name\n\n\ndef generate_main_fun(fun_names):\n print(\"fun main(execCtx: *ExecutionContext) -> int32 {\")\n print(\" var state: State\")\n for fun_name in fun_names:\n print(\" {}(execCtx, &state)\".format(fun_name))\n print(\" return state.OP_INTEGER_placeholder\")\n print(\"}\")\n\n\ndef generate_all():\n fun_names = []\n row_nums = list(range(10000, 100000, 10000)) + list(range(100000, 1000000, 100000))\n data_types = [\"OP_INTEGER\", \"OP_DECIMAL\"]\n operations = [\"PLUS_OR_MINUS\", \"MULTIPLY\", \"DIVIDE\", \"COMPARE\"]\n\n generate_state()\n\n for row_num in row_nums:\n for data_type in data_types:\n for operation in operations:\n fun_names.append(generage_arithmetic_fun(row_num, data_type, operation))\n\n generate_main_fun(fun_names)\n\n\nif __name__ == '__main__':\n generate_all()\n","sub_path":"script/model/execution_engine_runner/generate_arithmetic.py","file_name":"generate_arithmetic.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307041487","text":"import sys\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nfrom skimage.measure import compare_mse, compare_psnr, compare_ssim\nfrom collections import OrderedDict\n\n\nROWS = 288 # 192 288\nCOLS = 360 # 240 360\n\n\ndef make_iter0_png(root='train_save_all'):\n first_batch_num = None\n for filename in os.listdir(root):\n img_path = os.path.join(root, filename)\n img_name = os.path.splitext(filename)\n if not os.path.isfile(img_path):\n continue\n\n if img_name[1] != '.png':\n continue\n\n substr = 'batch'\n p = img_name[0].find(substr)\n batch_num = img_name[0][p + len(substr):p + len(substr) + 6]\n\n if first_batch_num != batch_num and first_batch_num is None:\n image = cv2.imread(img_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR)\n image[:, COLS:2 * COLS] = image[:, :COLS]\n image[:, 3 * COLS:4 * COLS] = np.abs(\n image[:, COLS:2 * COLS].astype(np.int32) - image[:, 2 * COLS:3 * COLS].astype(np.int32))\n cv2.imwrite(img_path.replace(str(batch_num), '000000'), image)\n first_batch_num = batch_num\n continue\n\n if batch_num == first_batch_num:\n image = cv2.imread(img_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR)\n image[:, COLS:2 * COLS] = image[:, :COLS]\n image[:, 3 * COLS:4 * COLS] = np.abs(\n image[:, COLS:2 * COLS].astype(np.int32) - image[:, 2 * COLS:3 * COLS].astype(np.int32))\n cv2.imwrite(img_path.replace(str(batch_num), '000000'), image)\n\n\ndef calc_ssim_psnr(image_path, sp_list, use_training_gmap_batch=True):\n img = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR)\n\n if use_training_gmap_batch:\n p0 = image_path.find('test')\n p1 = image_path.find('.png')\n gmaps_name = 'batch_' + image_path[p0: p1] + '_gmap.npy'\n path = os.path.split(image_path)[0]\n gmaps = np.load(os.path.join(path, gmaps_name))\n\n idx_col = img.shape[1] // COLS - 3\n batch_size = img.shape[0] // ROWS\n\n mean_psnr_pred = 0.0\n mean_ssim_pred = 0.0\n\n for i in range(batch_size):\n pred = img[i * ROWS:(i + 1) * ROWS, 1 * COLS:2 * COLS]\n label = img[i * ROWS:(i + 1) * ROWS, 2 * COLS:3 * COLS]\n\n pred = pred.astype(np.float32) / 255.\n label = label.astype(np.float32) / 255.\n\n if use_training_gmap_batch:\n gmap = np.squeeze(gmaps[i])\n pred = np.clip(pred * gmap, 0.0, 1.0)\n label = np.clip(label * gmap, 0.0, 1.0)\n\n mean_psnr_pred += compare_psnr(label, pred)\n mean_ssim_pred += compare_ssim(label, pred)\n\n mean_psnr_pred /= batch_size\n mean_ssim_pred /= batch_size\n\n if len(sp_list) == 0:\n sp_list.append(mean_psnr_pred)\n sp_list.append(mean_ssim_pred)\n else:\n sp_list[0] += mean_psnr_pred\n sp_list[1] += mean_ssim_pred\n\n\ndef gen_label(path):\n if path.endswith(os.path.sep) or path.endswith(os.path.altsep):\n path = path[:-1]\n\n label = os.path.split(path)[1]\n label = label.replace('train_save_all_', '')\n\n return label\n\n\ndef make_psnr_ssim_curve(root='train_save_all', use_gmap=True):\n ps_dict = OrderedDict()\n img_cnt_per_iter = 0\n\n for img in os.listdir(root):\n img_path = os.path.join(root, img)\n img_name = os.path.splitext(img)\n if not os.path.isfile(img_path):\n continue\n\n if img_name[1] != '.png':\n continue\n\n substr = 'batch'\n p = img_name[0].find(substr)\n iter = int(img_name[0][p + len(substr):p + len(substr) + 6])\n\n if iter not in ps_dict.keys():\n ps_dict[iter] = list()\n\n calc_ssim_psnr(img_path, ps_dict[iter], use_training_gmap_batch=use_gmap)\n\n img_cnt_per_iter += 1\n\n img_cnt_per_iter /= len(ps_dict.keys())\n\n for k, val in ps_dict.items():\n for i, _ in enumerate(val):\n ps_dict[k][i] /= img_cnt_per_iter\n\n label = gen_label(root)\n print('Done: ', label)\n\n return ps_dict, label\n\n\ndef draw_psnr_ssim(ps_dict_list, labels):\n fig = plt.figure()\n ax_psnr = fig.add_subplot(2, 1, 1)\n ax_psnr.set_ylabel(\"PSNR\")\n\n ax_ssim = fig.add_subplot(2, 1, 2)\n ax_ssim.set_ylabel(\"SSIM\")\n\n ax_ssim.set_xlabel(\"iteration\")\n\n marker_styles = ['bs', 'gp', 'c+', 'mx', 'k*', 'yo', 'm.', 'bh']\n\n for i, ps_dict in enumerate(ps_dict_list):\n x = []\n y_psnr = []\n y_ssim = []\n for k, val in ps_dict.items():\n x.append(k)\n y_psnr.append(val[0])\n y_ssim.append(val[1])\n\n ax_psnr.plot(x, y_psnr, marker_styles[i], label=labels[i])\n ax_ssim.plot(x, y_ssim, marker_styles[i])\n\n ax_psnr.legend(loc=0)\n\n save_png_name = time.strftime('diagram/ps_%Y%m%d%H%M%S.png', time.localtime(time.time()))\n fig.savefig(save_png_name)\n plt.show()\n plt.close()\n\n\nif __name__ == '__main__':\n '''\n # [ori dataset] [in/G, label/G] \"ps_model_2.png\"\n # psnr(label/G, out) -> psnr(label, out*G) -> psnr(label, out*G){*diff data location}\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0518_1730', use_gmap=False)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0518_1730', use_gmap=True)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1])\n '''\n\n '''\n # [gl dataset] \"ps_model_3.png\"\n # 3 * net, 2 * block -> 1 * net, 3 * block -> 1 * net, 4 * block\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0519_1425', use_gmap=False)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0519_2000', use_gmap=False)\n psnr_ssim_2 = make_psnr_ssim_curve('train_save_all_0521_1200', use_gmap=False)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, psnr_ssim_2])\n '''\n\n '''\n # [ori dataset] [without Gmap] a little better, robuster \"ps_model_5.png\"\n # output := output -> output := input - output\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_noG', use_gmap=False)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0521_1630', use_gmap=False)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, ])\n \n # [ori dataset] [with Gmap] a little better, robuster \"ps_model_6.png\"\n # output := output -> output := input - output\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0518_1730', use_gmap=True)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0521_1830', use_gmap=True)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, ])\n '''\n\n '''\n # [ori dataset] [with Gmap] using lrelu, a little better \"ps_model_7.png\"\n # relu -> lrelu\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0521_1830', use_gmap=True)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0522_1130', use_gmap=True)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, ])\n '''\n\n '''\n # [ori dataset] [with Gmap] remove dc operation \"ps_model_8.png\"\n # relu -> lrelu\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0521_1830', use_gmap=True)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0522_1350', use_gmap=True)\n psnr_ssim_2 = make_psnr_ssim_curve('train_save_all_0522_1350', use_gmap=False)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, psnr_ssim_2])\n '''\n\n '''\n # [ori dataset] new\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0522_1900', use_gmap=False)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0522_2030', use_gmap=False)\n psnr_ssim_2 = make_psnr_ssim_curve('train_save_all_0522_2230', use_gmap=False)\n psnr_ssim_3 = make_psnr_ssim_curve('train_save_all_0522_1930', use_gmap=False)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, psnr_ssim_2, psnr_ssim_3])\n '''\n\n '''\n # [ori dataset] unet densenet \"ps_model_20.png\"\n # unet + 1x1 convs -> unet + 1x1 convs + rm last 3 bn -> unet + rm last several bns\n psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_0524_1250', use_gmap=False)\n psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_0524_1255', use_gmap=False)\n psnr_ssim_2 = make_psnr_ssim_curve('train_save_all_0524_1609', use_gmap=False)\n psnr_ssim_3 = make_psnr_ssim_curve('train_save_all_0522_1930', use_gmap=False)\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1, psnr_ssim_2, psnr_ssim_3])\n '''\n\n data_dir0 = 'D:/Dataset/MRI/Thrive/0803/tfrecords/thrive_train_norm3_intep_a4_n060/train_save_all_intep_a4_n060'\n psnr_ssim_0, label0 = make_psnr_ssim_curve(data_dir0, use_gmap=False)\n\n data_dir1 = 'D:/Dataset/MRI/Thrive/0803/tfrecords/thrive_train_norm3_intep_a4_n060/train_save_all_intep_a4_n060_unet'\n psnr_ssim_1, label1 = make_psnr_ssim_curve(data_dir1, use_gmap=False)\n\n data_dir2 = 'D:/Dataset/MRI/Thrive/0803/tfrecords/thrive_train_norm3_intep_a2_n080/train_save_all'\n # psnr_ssim_2, label2 = make_psnr_ssim_curve(data_dir2, use_gmap=False)\n\n data_dir3 = 'D:/Dataset/MRI/Thrive/0803/tfrecords/thrive_train_norm3_intep_a4_n050-100/train_save_all'\n # psnr_ssim_3, label3 = make_psnr_ssim_curve(data_dir3, use_gmap=False)\n\n draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1],\n [label0, label1])\n\n # use gan\n # psnr_ssim_0 = make_psnr_ssim_curve('train_save_all_2rnn', use_gmap=False)\n # psnr_ssim_1 = make_psnr_ssim_curve('train_save_all_3rnn', use_gmap=False)\n # draw_psnr_ssim([psnr_ssim_0, psnr_ssim_1])\n\n # make_iter0_png()\n print('done')\n","sub_path":"denoise_py/snr_demo.py","file_name":"snr_demo.py","file_ext":"py","file_size_in_byte":9353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"531759701","text":"r\"\"\"\n\n在对隐藏层使用丢弃法,假设其中 h2, h5被清零,那么输出值的计算不再依赖于 h2, h5,在反向传播时,与这两个隐藏层相关的权重的梯度均为0.\n由于在训练中,每个神经元都有概率被清零,因此输出层的计算无法过度依赖于h1,...,h5中的任意一个,从而在训练模型时起到正则化的作用,并可\n能用力应对过拟合。在测试模型时,我们为了得到更加确定的结果,一般不使用丢弃法。\n\"\"\"\n\nfrom d2lzh import d2l\nfrom mxnet.gluon import loss as gloss, data as gdata\nfrom mxnet import autograd, nd\n\n\ndef dropout(X, drop_prob):\n r'''\n 公式:\n h_i' = (ξ_i / (1 - drop_prob)) * h_i\n 其中 ξ_i 是丢弃神经元的概率,设 ξ_i 为 0 和 1 的概率分别为 p 和 1-p。\n\n 期望算法:\n E(h_i') = (E(ξ_i) / (1 - drop_prob)) * E(h_i)\n = ((1 - drop_prob) / (1 - drop_prob)) * E(h_i)\n = E(h_i)\n 期望不变\n\n :param X:\n :param drop_prob:\n :return:\n '''\n assert 0 < drop_prob < 1\n keep_prob = 1 - drop_prob\n if keep_prob == 0:\n return nd.zeros_like()\n mask = nd.random.uniform(0, 1, X.shape) < keep_prob\n X_final = mask * X / keep_prob\n # print('mask : {}'.format(mask))\n return X_final\n\n\nnum_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256\nW1 = nd.random.normal(scale=0.01, shape=(num_inputs, num_hiddens1))\nb1 = nd.zeros(num_hiddens1)\nW2 = nd.random.normal(scale=0.01, shape=(num_hiddens1, num_hiddens2))\nb2 = nd.zeros(num_hiddens2)\nW3 = nd.random.normal(scale=0.01, shape=(num_hiddens2, num_outputs))\nb3 = nd.zeros(num_outputs)\n\nparams = [W1, b1, W2, b2, W3, b3]\n\n\ndef net(X):\n for param in params:\n param.attach_grad()\n\n drop_prob1, drop_prob2 = 0.2, 0.5\n\n X = X.reshape(-1, num_inputs)\n H1 = (nd.dot(X, W1) + b1).relu()\n if autograd.is_training(): # 只有在训练时,使用drop_out\n keep_prob = 1 - drop_prob1\n mask = nd.random.normal(0, 1, H1.shape) < keep_prob\n H1 = mask * H1 / keep_prob\n H2 = (nd.dot(H1, W2) + b2).relu()\n if autograd.is_training():\n keep_prob = 1 - drop_prob2\n mask = nd.random.normal(0, 1, H2.shape) < keep_prob\n H2 = H2 * mask / keep_prob\n return nd.dot(H2, W3) + b3\n\n\ndef train():\n num_epochs, lr, batch_size = 5, 0.5, 256\n loss = gloss.SoftmaxCrossEntropyLoss()\n train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,\n params, lr)\n\n\ndef dropout_test():\n X = nd.arange(16).reshape((2, 8))\n X_d = dropout(X, 0.2)\n print('X_d : {}'.format(X_d))\n X_d = dropout(X, 0.5)\n print('X_d : {}'.format(X_d))\n X_d = dropout(X, 0.8)\n print('X_d : {}'.format(X_d))\n\n\nif __name__ == '__main__':\n train()\n","sub_path":"chapter3/C_3_13_dropout.py","file_name":"C_3_13_dropout.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"444617464","text":"import numpy as np\n\nfrom doctr.models import detection\n\n\ndef test_dbpostprocessor():\n postprocessor = detection.DBPostProcessor(rotated_bbox=False)\n r_postprocessor = detection.DBPostProcessor(rotated_bbox=True)\n mock_batch = np.random.rand(2, 512, 512).astype(np.float32)\n out, _ = postprocessor(mock_batch)\n r_out, _ = r_postprocessor(mock_batch)\n # Batch composition\n assert isinstance(out, list)\n assert len(out) == 2\n assert all(isinstance(sample, np.ndarray) for sample in out)\n assert all(sample.shape[1] == 5 for sample in out)\n assert all(sample.shape[1] == 6 for sample in r_out)\n # Relative coords\n assert all(np.all(np.logical_and(sample[:, :4] >= 0, sample[:, :4] <= 1)) for sample in out)\n assert all(np.all(np.logical_and(sample[:, :4] >= 0, sample[:, :4] <= 1)) for sample in r_out)\n # Repr\n assert repr(postprocessor) == 'DBPostProcessor(box_thresh=0.1)'\n # Edge case when the expanded points of the polygon has two lists\n issue_points = np.array([\n [869, 561],\n [923, 581],\n [925, 595],\n [915, 583],\n [889, 583],\n [905, 593],\n [882, 601],\n [901, 595],\n [904, 604],\n [876, 608],\n [915, 614],\n [911, 605],\n [925, 601],\n [930, 616],\n [911, 617],\n [900, 636],\n [931, 637],\n [904, 649],\n [932, 649],\n [932, 628],\n [918, 627],\n [934, 624],\n [935, 573],\n [909, 569],\n [934, 562]], dtype=np.int32)\n out = postprocessor.polygon_to_box(issue_points)\n r_out = r_postprocessor.polygon_to_box(issue_points)\n assert isinstance(out, tuple) and len(out) == 4\n assert isinstance(r_out, tuple) and len(r_out) == 5\n\n\ndef test_linknet_postprocessor():\n postprocessor = detection.LinkNetPostProcessor()\n r_postprocessor = detection.LinkNetPostProcessor(rotated_bbox=True)\n mock_batch = np.random.rand(2, 512, 512).astype(np.float32)\n out, _ = postprocessor(mock_batch)\n r_out, _ = r_postprocessor(mock_batch)\n # Batch composition\n assert isinstance(out, list)\n assert len(out) == 2\n assert all(isinstance(sample, np.ndarray) for sample in out)\n assert all(sample.shape[1] == 5 for sample in out)\n assert all(sample.shape[1] == 6 for sample in r_out)\n # Relative coords\n assert all(np.all(np.logical_and(sample[:4] >= 0, sample[:4] <= 1)) for sample in out)\n","sub_path":"tests/common/test_models_detection.py","file_name":"test_models_detection.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"342703501","text":"import pygame\nimport logic\nimport surface\nimport service\n\nSCREEN_DIM = (1180, 675)\n\n\npygame.init()\ngame_display = pygame.display.set_mode(SCREEN_DIM)\npygame.display.set_caption('Arena')\n\n\nservice.service_init()\n\n\ndef create_game(is_new=False):\n global engine, drawer\n if is_new:\n engine = logic.GameEngine()\n drawer = surface.ArenaSurface(\n (1180, 675),\n pygame.SRCALPHA,\n (0, 0),\n surface.ScreenHandle((0, 0))\n )\n\n drawer.connect_engine(engine)\n service.reload_game(engine)\n\n\ncreate_game(True)\n\nwhile engine.working:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n engine.working = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n engine.working = engine.game_process\n engine.game_process = False\n if engine.game_process:\n if event.key == pygame.K_SPACE:\n engine.start_fighting()\n if event.key == pygame.K_RETURN:\n engine.end_fighting()\n\n game_display.blit(drawer, (0, 0))\n drawer.draw(game_display)\n pygame.display.update()\n\npygame.display.quit()\npygame.quit()\nexit(0)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"328525366","text":"from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException\nimport string\nimport random\n\n\n# method for dropdown grid category view\nfrom selenium_tests.models import TestRunsExecution\n\n\ndef drop_down_list_element_finder(dropdowngrid_pageobject):\n a = False\n while a is False:\n try:\n if dropdowngrid_pageobject.get_single_element_from_drop_down_list(\n \"Exercise\",\n \"Ea\",\n \"1.1\",\n ).is_displayed() is True:\n a = True\n else:\n raise NoSuchElementException\n except (NoSuchElementException, ElementNotVisibleException):\n try:\n print(\"first level exception\")\n dropdowngrid_pageobject.get_scroll_down_button().click()\n except (NoSuchElementException, ElementNotVisibleException):\n print(\"second level exception\")\n break\n\n\ndef random_string_generator(size):\n output =str(\"\")\n for x in range(0,size,1):\n output+=(random.choice(string.ascii_letters))\n return output.lower()\n\n\ndef slower_than_prevoius_run(test_run_minutes, test_run_seconds):\n single_value_from_actual_run = float(test_run_minutes * 60) + test_run_seconds\n try:\n last_run_minutes = TestRunsExecution.objects.values().last().get(\n \"execution_time_minutes\"\n )\n last_run_seconds = TestRunsExecution.objects.values().last().get(\n \"execution_time_seconds\"\n )\n except AttributeError:\n last_run_minutes = 99\n last_run_seconds = 99\n\n single_value_from_previous_run = (last_run_minutes * 60) + last_run_seconds\n if single_value_from_actual_run > single_value_from_previous_run:\n return True\n return False\n","sub_path":"selenium_tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"299948804","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import String\nfrom turtlesim.msg import Pose\nfrom math import pow,atan2,sqrt\nfrom PlannedPath import PlannedPath\nfrom ControllerBase import ControllerBase\nimport sys\nimport time\nimport math\n\nclass Move2GoalController(ControllerBase):\n\n def __init__(this, occupancyGrid):\n ControllerBase.__init__(this, occupancyGrid)\n\n def get_distance(self, goal_x, goal_y):\n distance = sqrt(pow((goal_x - self.pose.x), 2) + pow((goal_y - self.pose.y), 2))\n return distance\n\n def get_angle(self, goal_x, goal_y):\n toAngle = atan2(goal_y - self.pose.y, goal_x - self.pose.x)\n fromAngle = self.pose.theta\n delta = toAngle - fromAngle\n while (delta < -math.pi): delta += 2.0*math.pi\n while (delta > math.pi): delta -= 2.0*math.pi\n return delta\n\n def driveToWaypoint(this, waypoint):\n vel_msg = Twist()\n\n # Calculate initial distance and angle error\n distanceError = this.get_distance(waypoint[0], waypoint[1])\n angleError = this.get_angle(waypoint[0], waypoint[1])\n\n this.distanceTravelled += distanceError\n this.angleTurned += math.fabs(angleError)\n\n # Move to waypoint\n while ((distanceError >= this.distance_tolerance) & (not rospy.is_shutdown())):\n \n # Only move when angle error is reduced below 1e-3\n if (math.fabs(angleError) < 1e-3):\n vel_msg.linear.x = 20 * distanceError\n\n # Continue reducing angle error even when moving\n vel_msg.angular.z = 20 * angleError\n\n this.velocityPublisher.publish(vel_msg)\n this.rate.sleep()\n \n # Update errors\n distanceError = this.get_distance(waypoint[0], waypoint[1])\n angleError = this.get_angle(waypoint[0], waypoint[1])\n\n # Stop moving\n vel_msg.linear.x = 0\n vel_msg.angular.z =0\n this.velocityPublisher.publish(vel_msg)\n","sub_path":"src/planner_controller/scripts/controller/Move2GoalController.py","file_name":"Move2GoalController.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"135357338","text":"# media, mediana, moda\nimport statistics as st\n\n\ndef media(lista):\n media = sum(lista) / len(lista)\n return media\n\ndef media_stats(lista):\n media = st.mean(lista)\n return media\n\ndef mediana(lista):\n lista_ordenada = sorted(lista)\n tamanho = len(lista_ordenada)\n\n if tamanho % 2 == 0:\n mediana = (lista_ordenada[int(tamanho/2)] + lista_ordenada[int((tamanho/2) - 1)]) / 2\n elif tamanho % 2 == 1:\n mediana = lista_ordenada[int(tamanho/2)]\n return mediana\n\ndef mediana_stats(lista):\n mediana = st.median(lista)\n return mediana\n\ndef moda(lista):\n numeros = {}\n for num in lista:\n if num not in numeros:\n numeros[num] = 1\n else:\n numeros[num] += 1\n\n maior_repeticao = max(numeros.values())\n for i in numeros:\n if numeros[i] == maior_repeticao:\n moda = i\n return moda\n\ndef moda_stats(lista):\n moda = st.mode(lista)\n return moda","sub_path":"python-intermediary/modularizacao/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"535084900","text":"from logging import getLogger, StreamHandler, INFO, DEBUG\n\nimport cv2\nfrom PyQt5.QtCore import QObject, pyqtSignal\n\nhandler = StreamHandler()\nhandler.setLevel(DEBUG)\nlogger = getLogger(__name__)\nlogger.setLevel(DEBUG)\nlogger.addHandler(handler)\nlogger.propagate = False\n\nclass UploadWorker(QObject):\n\n uploaded = pyqtSignal(object)\n\n def __init__(self, parent, config, api, name):\n QObject.__init__(self)\n self.parent = parent\n self.config = config\n self.api = api\n self.name = name\n\n def upload(self):\n self.api.uploadPhoto(self.name, caption=self.config.instagram_caption)\n self.uploaded.emit(True)\n","sub_path":"gui/upload_worker.py","file_name":"upload_worker.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"265928597","text":"from collections import Counter, namedtuple\nimport csv\nimport re\nfrom pprint import pprint\n\nimport requests\n\nMARVEL_CSV = 'https://raw.githubusercontent.com/pybites/marvel_challenge/master/marvel-wikia-data.csv' # noqa E501\n\nCharacter = namedtuple('Character', 'pid name sid align sex appearances year')\n\n\n# csv parsing code provided so this Bite can focus on the parsing\n\ndef _get_csv_data():\n \"\"\"Download the marvel csv data and return its decoded content\"\"\"\n with requests.Session() as session:\n return session.get(MARVEL_CSV).content.decode('utf-8')\n\n\ndef load_data():\n \"\"\"Converts marvel.csv into a sequence of Character namedtuples\n as defined above\"\"\"\n content = _get_csv_data()\n reader = csv.DictReader(content.splitlines(), delimiter=',')\n for row in reader:\n name = re.sub(r'(.*?)\\(.*', r'\\1', row['name']).strip()\n yield Character(pid=row['page_id'],\n name=name,\n sid=row['ID'],\n align=row['ALIGN'],\n sex=row['SEX'],\n appearances=row['APPEARANCES'],\n year=row['Year'])\n\n\ncharacters = list(load_data())\n\n\n# start coding\n\ndef get_appearances(c : Character) -> int:\n try:\n return int(c.appearances)\n except ValueError as _:\n return 0\n\ndef most_popular_characters(characters=characters, top=5):\n \"\"\"Get the most popular character by number of appearances,\n return top n characters (default 5)\n \"\"\"\n name_ctr = Counter({c: int(get_appearances(c))\n for c in characters})\n \n return [c[0].name for c in name_ctr.most_common(top)]\n\n\n\ndef max_and_min_years_new_characters(characters=characters):\n \"\"\"Get the year with most and least new characters introduced respectively,\n use either the 'FIRST APPEARANCE' or 'Year' column in the csv\n characters, or the 'year' attribute of the namedtuple, return a tuple\n of (max_year, min_year)\n \"\"\"\n intro_ctr = Counter(c.year for c in characters if c.year)\n ranking = intro_ctr.most_common()\n return ranking[0][0], ranking[-1][0]\n\n\ndef get_percentage_female_characters(characters=characters):\n \"\"\"Get the percentage of female characters as percentage of all genders\n over all appearances.\n Ignore characters that don't have gender ('sex' attribue) set\n (in your characters data set you should only have Male, Female,\n Agender and Genderfluid Characters.\n Return the result rounded to 2 digits\n \"\"\"\n sexes = [c.sex for c in characters if c.sex]\n sex_ctr = Counter(sexes)\n females = sex_ctr['Female Characters']\n total = sum(sex_ctr.values())\n return round(100 * females / total,2)","sub_path":"124/marvel.py","file_name":"marvel.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"398558274","text":"#%% Import relevant modules\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport keras as K\n\n#%% Load train data\nfolderData = 'Data\\\\'\nfolderResults = 'Results\\\\'\nfolderModels = 'TrainedModels\\\\'\n\ntrainData = pd.read_csv(folderData+'train.csv')\n# Get image and label from trainData\nlabelTrain = trainData['label']\nimageTrain = trainData.drop(\"label\",axis=1)\n# One hot encoding of the labels\nlabelTrainOneHot = K.utils.to_categorical(labelTrain)\n#%% Choose some image to displays\nnTrain = imageTrain.shape[0]\nnRow = 4\nnCol = 7\nidx = np.random.choice(np.arange(nTrain), nRow*nCol)\n# Plot somes images\nplt.figure(figsize=(13,12))\nfor i in range(nRow * nCol):\n plt.subplot(nRow, nCol, i + 1)\n plt.imshow(imageTrain.values[idx[i],:].reshape(28,28),cmap='gray')\n title_text = 'Image ' + str(i + 1) + ' labeled ' + str(labelTrain[idx[i]])\n plt.title(title_text, size=6.5)\n plt.xticks(())\n plt.yticks(())\nplt.show()\n\n#%% Setup a DNN\n# Get input dimension\ndInput = imageTrain.shape[1]\n# Number of units for the hidden layer\nnUnits = 1000\n# Number of classes to predict\nnClasses = 10\n\n# Construct the DNN : one input layer, one hidden layer and one output layer\ninputLayer = K.layers.Input((dInput,),name='inputLayer')\ndenseLayer_1 = K.layers.Dense(nUnits,activation='relu')(inputLayer)\ndenseLayer_2 = K.layers.Dense(nClasses,activation='relu')(denseLayer_1)\n# Add softmax layer for class probability computation\noutputLayer = K.layers.Softmax()(denseLayer_2)\n# Gather the layers into a keras model\nmodel = K.Model(inputs=inputLayer, outputs=outputLayer)\n# Compile the model with ADAM optimizer and binary crossentropy loss\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['binary_accuracy'])\n# Fit the DNN model by batch of 128 samples and for 10 epochs\nmodel.fit(imageTrain,labelTrainOneHot,batch_size=128,epochs=10)\n# Save the trained model\nmodel.save('TrainedModel\\\\myDNN.h5')\n\n#%% Lood test data\ntestData = pd.read_csv(folderData+'test.csv')\n# Get image from testData\nimageTest = testData\n#%% Predict on test data\nlabelPredicted = model.predict(imageTest)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"158795111","text":"NumeroFinalDoIntervalo = int(input(\"Qual numero você quer verificar os numeros primos no intervalo de [1,X], com X valendo? \" ))\nwhile NumeroFinalDoIntervalo <= 1 or NumeroFinalDoIntervalo > 1000:\n print(\"Numero invalido, seu numero deve ser igual ou maior a 2 e menor ou igual a 1000\")\n NumeroFinalDoIntervalo = int(input(\"Qual numero você quer verificar os numeros primos no intervalo de [1,X], com X valendo? \" ))\nprint(\"Entre 1 e\",NumeroFinalDoIntervalo,\"são primos os números:\")\nNumerosAVerificarDoMeioDoIntervalo = 2\nwhile NumerosAVerificarDoMeioDoIntervalo <= NumeroFinalDoIntervalo-1:\n NumeroDeDivisoresPossivel = 0\n NumeroParaComparacaoInicial = 1\n while NumeroParaComparacaoInicial < 1000:\n if NumerosAVerificarDoMeioDoIntervalo % NumeroParaComparacaoInicial == 0:\n NumeroDeDivisoresPossivel = NumeroDeDivisoresPossivel + 1\n NumeroParaComparacaoInicial = NumeroParaComparacaoInicial + 1 \n if NumeroDeDivisoresPossivel == 2:\n print(NumerosAVerificarDoMeioDoIntervalo,end=\" \") \n NumerosAVerificarDoMeioDoIntervalo = NumerosAVerificarDoMeioDoIntervalo + 1","sub_path":"Lista 3/lista03ex21.py","file_name":"lista03ex21.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"647702326","text":"\"\"\"\nrepoaccess.txt editing functions for repoedit.\n\"\"\"\n\nimport sys, re, os\n\nclass RepoObject:\n\t\"\"\" Generic Repo object as contained in repository entries. \"\"\"\n\tdef __init__(self, name, rights, parent=None):\n\t\tself.name = name\n\t\tself.access_rights = rights\n\t\tself.repo = parent\n\n\tdef set_rights(rights):\n\t\t\"\"\" Sets the rights of the object. Valid values are \"rw\" and \"r\". \"\"\"\n\t\tif rights != \"rw\" or rights != \"r\":\n\t\t\traise Exception(\"Invalid access right type %s.\" % rights)\n\t\telse:\n\t\t\tself.access_rights = rights\n\t\t\treturn True\n\n\tdef output(self):\n\t\t\"\"\" Returns the string representation as it should look in\n\t\trepoaccess.txt. MUST BE OVERRIDDEN! \"\"\"\n\t\traise Exception(\"Base class called. Bad!\")\n\nclass RepoGroup(RepoObject):\n\t\"\"\" The RepoGroup is access for a group. They aren't currently used, but are\n\tfully supported by RepoEdit. \"\"\"\n\tdef output(self):\n\t\t\"\"\" Returns the string representation as it should look in\n\t\trepoaccess.txt \"\"\"\n\t\treturn \"@%s = %s\" % (self.name, self.access_rights)\n\nclass RepoUser(RepoObject):\n\t\"\"\" Represents a single user for a specific repository. \"\"\"\n\tdef output(self):\n\t\t\"\"\" Returns the string representation as it should look in\n\t\trepoaccess.txt \"\"\"\n\t\treturn \"%s = %s\" % (self.name, self.access_rights)\n\nclass GroupDef:\n\t\"\"\" Group definition defines a name of a group and the users that belong to\n\tit. \"\"\"\n\tdef __init__(self, name, members=None):\n\t\t\"\"\" Creates a new GroupDef object. If members is passed and is iterable,\n\t\tthe strings within are automatically added a members. \"\"\"\n\t\tself.name = name\n\t\tself.members = []\n\t\tif members is not None:\n\t\t\ttry:\n\t\t\t\titerator = iter(members)\n\n\t\t\t\tfor member in members:\n\t\t\t\t\tself.add_member(member)\n\t\t\texcept TypeError:\n\t\t\t\t# Cannot iterate. Ignore.\n\t\t\t\tpass\n\t\t\tfinally:\n\t\t\t\t# Finalized.\n\t\t\t\tdel iterator\n\n\tdef add_member(self, name):\n\t\t\"\"\" Adds a member to the group. Returns False if the member was already\n\t\tthere, True, otherwise. Case SENSITIVE. \"\"\"\n\t\tif name not in self.members:\n\t\t\tself.members.append(name)\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef del_member(self, name):\n\t\t\"\"\" Removes a member from the group. Returns False if the member was not\n\t\tfound, True otherwise. \"\"\"\n\t\tif name not in self.members:\n\t\t\treturn False\n\t\telse:\n\t\t\tself.members.remove(name)\n\t\t\treturn True\n\nclass Repo:\n\t\"\"\" Represents a single repository. \"\"\"\n\tdef __init__(self, name, path):\n\t\tself.name = name # The repo name.\n\t\tself.path = path # The repo's relative path.\n\t\tself.entries = {} # Dictionary of RepoEntry objects (either RepoUser or RepoGroup).\n\tdef set_user(self, user, rights):\n\t\t\"\"\" Sets (or adds) access rights for a *user* on this repo. \"\"\"\n\t\tif user in self.entries:\n\t\t\tif type(self.entries[user]) is not RepoUser:\n\t\t\t\tprint(\"Warning! Changing non-user as if they were a user!\")\n\t\t\t# Edit.\n\t\t\tself.entries[user].set_rights(rights)\n\t\telse:\n\t\t\tself.entries[user] = RepoUser(user, rights, self)\n\n\tdef set_group(self, group, rights):\n\t\t\"\"\" Sets (or adds) access rights for a *group* on this repo. \"\"\"\n\t\tif group in self.entries:\n\t\t\tif type(self.entries[user]) is not RepoGroup:\n\t\t\t\tprint(\"Warning! Changing non-group as if they were a group!\")\n\t\t\t# Edit.\n\t\t\tself.entries[group].set_rights(rights)\n\t\telse:\n\t\t\tself.entries[group] = RepoGroup(group, rights, self)\n\n\tdef del_user(self, user):\n\t\t\"\"\" Removes a user from the access list. Returns True if succesful,\n\t\tFalse if the group was not found. \"\"\"\n\t\tif user in self.entries and type(self.entries[user]) is RepoUser:\n\t\t\tdel self.entries[user]\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef del_group(self, group):\n\t\t\"\"\" Removes a group from the access list. Returns True if succesful,\n\t\tFalse if the group was not found. \"\"\"\n\t\tif group in self.entries and type(self.entries[group]) is RepoGroup:\n\t\t\tdel self.entries[group]\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass RepoAccess:\n\t\"\"\" Entire repoaccess representation. \"\"\"\n\tuser_regex = re.compile(\"(\\w+@[\\w\\.]\\.aau\\.dk) = (\\w*)\") # Matches a user access right.\n\tgroup_acl_regex = re.compile(\"(@\\w+) = (\\w*)\") # Matches a group access right..\n\tgroup_def_regex = re.compile(\"(\\w+) = (\\w+)(,\\s*\\w+)+\") # Matches a group definition.\n\trepo_def_regex = re.compile(\"\\[(\\w+):([\\w/]+)\\]\") # Matches a repo definition.\n\tdef __init__(self, path):\n\t\t\"\"\" Opens and parses a repoaccess.txt file. \"\"\"\n\t\ttry:\n\t\t\tfile = open(path, \"rt\")\n\t\tfinally:\n\t\t\tlines = file.readlines()\n\t\t\tfile.close()\n\t\t\tdel file # Done with you!\n\n\t\t# Set initial values.\n\t\tself.groups = {} # Dictionary of all defined acl groups.\n\t\tself.repos = {} # Dictionary of all defined repositories.\n\n\t\tlevel = 0 # 0 = root, 1 = within groups section, 2 = within a repo section.\n\t\tcurrent_repo = None\n\n\t\t# Parse-o-rama\n\t\tfor line in lines:\n\t\t\tparsed = False\n\t\t\twhile not parsed: # Allows us to return to level 0 parsing if an end-of-section was found.\n\t\t\t\tif level == 0:\n\t\t\t\t\t# Find next section type.\n\t\t\t\t\tuser = try_parse_repo(line)\n\t\t\t\t\tif user is not False:\n\t\t\t\t\t\tprint(\"Found repository %s.\" % user)\n\t\t\t\t\t\tcurrent_repo = self.repos[user]\n\t\t\t\t\t\tlevel = 2\n\t\t\t\t\t\tparsed = True\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tgroup = try_parse_group_section(line)\n\t\t\t\t\tif group is not False:\n\t\t\t\t\t\tprint(\"Found group definitions\")\n\t\t\t\t\t\tlevel = 1\n\t\t\t\t\t\tparsed = True\n\t\t\t\t\t\tcontinue # Force breaking from \n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Nothing found: '%s'. Moving on.\" % line)\n\t\t\t\t\t\t# Imperative we don't mess with parsed var here. This is the key continue point.\n\t\t\t\telif level == 1:\n\t\t\t\t\t# Find next group definition.\n\t\t\t\t\tgroup = try_parse_group_def(line)\n\t\t\t\t\tif group is not False:\n\t\t\t\t\t\tprint(\"Found new group %s.\" % group)\n\t\t\t\t\t\tparsed = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Could not parse a new group. Assuming end of section by '%s'.\" % line)\n\t\t\t\t\t\tlevel = 0\n\t\t\t\t\t\tparsed = False\n\t\t\t\telif level == 2:\n\t\t\t\t\t# Find next repo entry or nothing.\n\t\t\t\t\tgroup = try_parse_group(line, current_repo)\n\t\t\t\t\tif group is not False:\n\t\t\t\t\t\tprint(\"Added group %s to repo.\" % group)\n\t\t\t\t\t\tparsed = True\n\t\t\t\t\tuser = try_parse_user(line, current_repo)\n\t\t\t\t\tif user is not False:\n\t\t\t\t\t\tprint(\"Added user %s to repo.\" % user)\n\t\t\t\t\t\tparsed = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"No match found in '%s'. Assuming end of section.\" % line)\n\t\t\t\t\t\tparsed = False\n\t\t\t\t\t\tlevel = 0\n\n\tdef try_parse_user(self, line, repo):\n\t\t\"\"\" Attempts to parse the line as a user access right. Returns name if \n\t\tthis succeeded, False otherwise. \"\"\"\n\t\tmatch = re.search(RepoAccess.user_regex, line)\n\t\tif match:\n\t\t\tself.repos[repo.name].set_user(match.group(1), match.group(2), self)\n\t\t\treturn match.group(1)\n\t\telse:\n\t\t\treturn False\n\n\tdef try_parse_group(self, line, repo):\n\t\t\"\"\" Attempts to parse the line as a group access right. Returns name if \n\t\tthis succeeded, False otherwise. \"\"\"\n\t\tmatch = re.search(RepoAccess.group_acl_regex, line)\n\t\tif match:\n\t\t\tself.repos[repo.name].set_group(match.group(1), match.group(2), self)\n\t\t\treturn match.group(1)\n\t\telse:\n\t\t\treturn False\n\n\tdef try_parse_repo(self, line):\n\t\t\"\"\" Attempts to parse a line from repoaccess.txt as a repo definition.\n\t\tReturns the name of the repo if succesful, False otherwise. \"\"\"\n\t\tmatch = re.search(RepoAccess.repo_def_regex, line)\n\t\tif match:\n\t\t\tself.repos[match.group(1)] = Repo(match.group(1), match.group(2))\n\t\t\treturn match.group(1)\n\t\telse:\n\t\t\treturn False\n\n\tdef try_parse_group_def(self, line):\n\t\t\"\"\" Attempts to parse a group definition. Returns the name of the group\n\t\tif succesful, False otherwise. \"\"\"\n\t\tmatch = re.searcH(RepoAccess.group_def_regex, line)\n\t\tif match:\n\t\t\tgroup = GroupDef(match.group(1))\n\t\t\t# Add all members.\n\t\t\tfor iterator in range(2,match.lastindex):\n\t\t\t\tmember = match.group(iterator)\n\t\t\t\tgroup.add_member(member)\n\t\t\tself.groups[match.group(1)] = group\n\t\t\treturn group.name\n\t\telse:\n\t\t\treturn False\n\n\tdef try_parse_group_section(self, line):\n\t\t\"\"\" Determines if a group section follows. \"\"\"\n\t\treturn \"groups\" in line\n\n\tdef strip_username(self, name):\n\t\t\"\"\" Strips a username of invalid characters such as ',' and whitespaces.\n\t\tThis will not necessarily sanitize the name. \"\"\"\n\t\treturn name.strip(\", \\t\").rstrip(\", \\t\")\n","sub_path":"lib/repoaccess.py","file_name":"repoaccess.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"414497224","text":"from __future__ import division\nimport pdb\nimport numpy as np\n\nclass DecisionTreeNode:\n '''This class encapsulates a simple tree node, which contains information like\n the split attribute used, the valid values for that split attribute, the branches\n connected to this node, and a class label (if this node is a leaf node).'''\n def __init__(self):\n '''This method initializes the node.'''\n self.split_attr = -1\n self.split_attr_type = \"DISCRETE\"\n self.attr_values = []\n self.label = -1\n self.branches = []\n self.instances = None\n\n def add_branch(self, node):\n '''This method adds a branch to this node.'''\n self.branches.append(node)\n\n def __str__(self):\n '''This method pretty prints the node.\n Note: nodes are printed differently depending on if they \n are an interior or leaf node.'''\n if len(self.branches) == 0:\n node_str = \"class label: %d\" % self.label\n else:\n node_str = 'split attribute: %d, split attribute type: %s, split values: %s, split branches length: %d, split number of instances: %d' % \\\n (self.split_attr, self.split_attr_type,\n str(self.attr_values), len(self.branches), len(self.instances))\n return node_str\n\n def __repr__(self):\n '''This method pretty prints the node during debugging.'''\n return self.__str__()\n","sub_path":"Project 4/decision_tree_node.py","file_name":"decision_tree_node.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"311676430","text":"import copy\nHelper = projectRelativeImport('helpers', 'app/util', 'Helper')\n\n# Individual items being held in scrape.py Data collector\nclass CollectorItem:\n # Initializer\n def __init__(self, parentId, url):\n if type(parentId) is not int:\n raise TypeError('invalid type of parentId in CollectorItem __init__(), should be int')\n elif type(url) is not str:\n raise TypeError('invalid type of url input in CollectorItem __init__(), should be str')\n elif parentId < -1:\n raise ValueError('invalid value of parentId in CollectorItem __init__(), must be greater than or equal to negative one')\n\n # Values\n self.content = [] # array normally with only one value, but selector could return multiple values\n self.attempted = False\n self.title = ''\n self.headerOne = []\n self.saved = False\n self.parents = [parentId]\n self.children = []\n self.url = url\n self.id = None\n\n # returns a stringified clone, doesn't effect original\n def stringifyTags(self):\n clone = copy.copy(self)\n temp = ''\n for contentPart in clone.content:\n temp = temp + self.__cleanMe(contentPart)\n\n clone.content = temp\n clone.title = Helper.xstr(clone.title)\n\n temp = ''\n for tag in clone.headerOne:\n if tag is not None and tag != '':\n temp = temp + ' - ' + tag.get_text().strip()\n\n clone.headerOne = temp\n return clone\n\n # private tag to clean string for content\n def __cleanMe(self, soup):\n for script in soup([\"script\", \"style\"]): # remove all javascript and stylesheet code\n script.extract()\n # get text\n text = soup.get_text()\n # break into lines and remove leading and trailing white space on each\n lines = (line.strip() for line in text.splitlines())\n # break multi-headlines into a line each\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n # drop blank lines\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n return text\n","sub_path":"app/modules/scraping/scrapedItem.py","file_name":"scrapedItem.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"542534905","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nTesting file for ipfs-scripting module.\n\"\"\"\n\nimport unittest\nimport json\n\nfrom src import hive_setting\nfrom tests.utils.http_client import HttpClient\nfrom tests import init_test\nfrom tests.utils_v1 import test_common\n\n\nclass IpfsScriptingTestCase(unittest.TestCase):\n def __init__(self, method_name='runTest'):\n super().__init__(method_name)\n init_test()\n self.cli = HttpClient(f'/api/v2/vault')\n self.cli2 = HttpClient(f'/api/v2/vault', is_did2=True)\n self.file_name = 'ipfs-scripting/test.txt'\n self.file_content = 'File Content: 1234567890'\n # Owner's did and application did.\n self.did = self.cli.get_current_did()\n self.app_did = test_common.app_id\n\n @staticmethod\n def _subscribe():\n HttpClient(f'/api/v2').put('/subscription/vault')\n HttpClient(f'/api/v2', is_did2=True).put('/subscription/vault')\n\n @classmethod\n def setUpClass(cls):\n cls._subscribe()\n\n @classmethod\n def tearDownClass(cls):\n pass\n\n def __register_script(self, script_name, body):\n response = self.cli.put(f'/scripting/{script_name}', body)\n self.assertEqual(response.status_code, 200)\n return json.loads(response.text)\n\n def __call_script(self, script_name, body=None, is_raw=False):\n if body is None:\n body = dict()\n body['context'] = {\n 'target_did': self.did,\n 'target_app_did': self.app_did,\n }\n response = self.cli2.patch(f'/ipfs-scripting/{script_name}', body)\n self.assertEqual(response.status_code, 200)\n return response.text if is_raw else json.loads(response.text)\n\n def __set_and_call_script(self, name, set_data, run_data):\n self.__register_script(name, set_data)\n return self.__call_script(name, run_data)\n\n def __call_script_for_transaction_id(self, script_name, check_anonymous=False):\n response_body = self.__call_script(script_name, {\n \"params\": {\n \"path\": self.file_name\n }\n })\n self.assertEqual(type(response_body), dict)\n self.assertTrue(script_name in response_body)\n self.assertEqual(type(response_body[script_name]), dict)\n self.assertTrue('transaction_id' in response_body[script_name])\n if check_anonymous:\n self.assertTrue('anonymous_url' in response_body[script_name])\n self.assertTrue(response_body[script_name]['anonymous_url'].startswith(hive_setting.IPFS_PROXY_URL))\n return response_body[script_name]['transaction_id']\n\n def test01_file_upload(self):\n name = 'ipfs_upload_file'\n self.__register_script(name, {\n \"executable\": {\n \"output\": True,\n \"name\": name,\n \"type\": \"fileUpload\",\n \"body\": {\n \"path\": \"$params.path\"\n }\n }\n })\n response = self.cli2.put(f'/ipfs-scripting/stream/{self.__call_script_for_transaction_id(name)}',\n self.file_content.encode(), is_json=False)\n self.assertEqual(response.status_code, 200)\n\n def test02_file_download(self):\n name = 'ipfs_download_file'\n self.__register_script(name, {\n \"executable\": {\n \"output\": True,\n \"name\": name,\n \"type\": \"fileDownload\",\n \"body\": {\n \"path\": \"$params.path\"\n }\n }\n })\n response = self.cli2.get(f'/ipfs-scripting/stream/{self.__call_script_for_transaction_id(name)}')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.text, self.file_content)\n\n def test03_file_properties_without_params(self):\n name = 'ipfs_file_properties'\n body = self.__set_and_call_script(name, {'executable': {\n 'name': name,\n 'type': 'fileProperties',\n 'output': True,\n 'body': {\n 'path': self.file_name\n }}}, None)\n self.assertTrue(name in body)\n self.assertEqual(body[name]['size'], len(self.file_content))\n\n def test04_file_hash(self):\n name = 'ipfs_file_hash'\n body = self.__set_and_call_script(name, {'executable': {\n 'name': name,\n 'type': 'fileHash',\n 'output': True,\n 'body': {\n 'path': '$params.path'\n }}}, {'params': {\n 'path': self.file_name}})\n self.assertIsNotNone(body)\n\n def test05_get_anonymous_file(self):\n name = 'ipfs_get_anonymous_file'\n self.__register_script(name, {\n \"executable\": {\n \"output\": True,\n \"name\": name,\n \"type\": \"fileDownload\",\n \"body\": {\n \"path\": \"$params.path\"\n }\n },\n \"allowAnonymousUser\": True,\n \"allowAnonymousApp\": True\n })\n self.__call_script_for_transaction_id(name, check_anonymous=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/ipfs_scripting_test.py","file_name":"ipfs_scripting_test.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"28593187","text":"# Author: Berat Kurar\n# Date: 01/01/2021\n\nimport math as m\nfrom PIL import Image\n\nRo = 600.0\nRi = 520.0\n\ncir = [[0 for x in range(int(Ro * 2))] for y in range(int(Ro * 2))]\n\nimage = Image.open('h_3600.png')\npixels = image.load()\nwidth, height = image.size\n\ndef morph_img(img):\n list_image = [item for sublist in img for item in sublist]\n new_image = Image.new(\"L\", (len(img[0]), len(img)))\n new_image.putdata(list_image)\n new_image.save(\"circled_text_image.png\",\"PNG\")\n\nfor i in range(int(Ro)):\n # outer_radius = Ro*m.cos(m.asin(i/Ro))\n outer_radius = m.sqrt(Ro*Ro - i*i)\n for j in range(-int(outer_radius),int(outer_radius)):\n if i < Ri:\n # inner_radius = Ri*m.cos(m.asin(i/Ri))\n inner_radius = m.sqrt(Ri*Ri - i*i)\n else:\n inner_radius = -1\n if j < -inner_radius or j > inner_radius:\n x = Ro+j\n y = Ro-i\n angle = m.atan2(y-Ro,x-Ro)/2\n distance = m.sqrt((y-Ro)*(y-Ro) + (x-Ro)*(x-Ro))\n distance = m.floor((distance-Ri+1)*(height-1)/(Ro-Ri))\n cir[int(y)][int(x)] = pixels[int(width*angle/m.pi) % width, height-distance-1]\n y = Ro+i\n angle = m.atan2(y-Ro,x-Ro)/2\n distance = m.sqrt((y-Ro)*(y-Ro) + (x-Ro)*(x-Ro))\n distance = m.floor((distance-Ri+1)*(height-1)/(Ro-Ri))\n cir[int(y)][int(x)] = pixels[int(width*angle/m.pi) % width, height-distance-1]\n\nmorph_img(cir)","sub_path":"cb55_experiment/morph_text_image_to_circle.py","file_name":"morph_text_image_to_circle.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"405528044","text":"import discord\nfrom discord.ext import commands\nfrom util import send_embed_message, search_youtube\nfrom googletrans import Translator\nimport requests\n\nTRANSLATOR = Translator()\n\n\ndef setup(bot):\n bot.add_cog(General(bot))\n\n\nclass General(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.last_corona_virus_data = {}\n\n @commands.command(name=\"ysearch\")\n async def youtubeSearch(self, ctx, *searchStr):\n searchStr = ' '.join(map(str, searchStr))\n await ctx.send(f\"Searching \\'{searchStr}\\' on youtube...\")\n video_link = search_youtube(searchStr)\n if video_link != None:\n await ctx.send(f\"Found : {video_link}\")\n else:\n await ctx.send(\"I couldn't find anything\")\n\n @commands.command(pass_context=True, description=\"Example usage:\\n h!translate \\'I love you\\' german\")\n async def translate(self, ctx, toTranslate: str = \"\", toTranslateLanguage: str = \"en\"):\n if toTranslate == \"\":\n await send_embed_message(ctx, \"Gimme something to translate\")\n try:\n detect_language = TRANSLATOR.detect(toTranslate).lang\n print(f\"Language detected from {toTranslate}, {detect_language}\")\n translated = TRANSLATOR.translate(\n toTranslate, src=detect_language, dest=toTranslateLanguage).text\n await send_embed_message(ctx, f\"This:\\n{toTranslate.upper()}\\nMeans:\\n{translated.upper()}\")\n except ValueError:\n await send_embed_message(ctx, \"Error, type h!help translate\")\n\n @commands.command()\n async def quote(self, ctx, amount=1):\n if amount > 10:\n amount = 10\n\n for i in range(amount):\n data = requests.get(\"https://api.quotable.io/random\").json()\n await send_embed_message(ctx, author_name=data[\"author\"], content=data[\"content\"])","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"176997598","text":"print(\"Welcome to the magic 8-ball! May the furtunes ever be in your favor\")\n\nimport random\n\npredictions = [\"It is certain\", \"It is decidedly so\", \"Without a doubt\", \"Yes Definitely\", \"You may rely on it\", \"As I see it, yes\", \"Most likely\", \"Outlook good\", \"Yes\", \"Signs point to yes\", \"Reply hazy try again\", \"Ask again later\", \"Better not to tell you\", \"Cannot predict now\", \"Concentrate and ask again\", \"Don't count on it\", \"My reply is no\", \"My sources say no\", \"Outlook not so good\", \"Very doubtful\"]\n\nask_question = input(\"Do you want to ask the Magic 8-Ball a question? (yes) or (no)\\n> \")\n\ncondition = True\n\nwhile condition:\n while ask_question.lower() not in [\"yes\", \"no\", \"done\"]:\n ask_question = input(\"I'm looking for a (yes) or (no/done)\\n> \")\n if ask_question.lower() == \"yes\":\n user_question = input(\"What question do you dare ask the Magic 8-Ball!?\\n> \")\n print(\"...\\n...\\n...\")\n print(f\"You have asked {user_question}; the Magic 8-Ball says: {random.choice(predictions)}.\")\n ask_question = input(\"Do you want to try again? or are you done?\\n> \")\n if ask_question.lower() == \"done\" or \"no\":\n print(\"Not everyone is ready for answers\")\n condition = False\n","sub_path":"python labs/lab4-magic_8_ball.py","file_name":"lab4-magic_8_ball.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"637273092","text":"'''\nCreated on Oct 21, 2014\n\n@author: JBlackmore\n'''\nimport sys\nfrom Tkinter import *\nfrom gold.models.board import Board, IllegalMove\nfrom gold.models.life import determineLife\nfrom gold.models.MoveTreeParser import MoveTreeParser\n\nDEFAULT_WIDTH = 400\nDEFAULT_HEIGHT = 400\nDEFAULT_MARGIN = 12\nDEFAULT_SPACES = 19\n\n''' Places a stone of color 'color' on the\n space nearest (x, y) on Canvas C.\n'''\nclass ResizingCanvas(Canvas):\n def __init__(self, parent, launcher, **kwargs):\n Canvas.__init__(self, parent, **kwargs)\n self.parent=parent\n self.bind('', self.on_resize)\n self.launcher = launcher\n \n def on_resize(self, event):\n self.parent.update()\n self.width = self.parent.winfo_width()\n self.height = self.parent.winfo_height()-42 # for the title bar I guess\n self.launcher.resize(self.width, self.height)\n \nclass Launcher:\n def __init__(self, dim_x, dim_y, margin, spaces, board=None):\n self.dim_x = dim_x\n self.dim_y = dim_y\n self.margin = margin\n self.spaces = spaces\n self.ovals=[]\n if board==None:\n self.board = Board(spaces, spaces)\n else:\n self.board = board\n self.spaces = max(board.x, board.y)\n self.diam = (float(dim_x)-2*float(margin))/float(self.spaces-1)\n self.master = Tk()\n self.master.resizable(True, True)\n self.master.configure(bg='#d8af4f')\n #self.board_frame = Frame(width=self.dim_x, height=dim_y, bg='#d8af4f')\n #self.board_frame.pack(side=TOP, fill=BOTH, expand=YES)\n #self.scaler_frame =Frame(width=self.dim_x, height=42, bg='#d8af4f')\n #self.scaler_frame.pack(side=BOTTOM, fill=X, expand=YES)\n self.C = None\n self.drawGrid()\n self.master.rowconfigure(0, weight=1)\n self.master.columnconfigure(0, weight=1)\n def callback(event):\n #[i, j] = self.computeSpace(event.x, event.y)\n self.placeStoneNear(event.x, event.y, 'white')\n def callback2(event):\n #[i, j] = self.computeSpace(event.x, event.y)\n self.placeStoneNear(event.x, event.y, 'black')\n #self.goForWhite(i, j)\n # Left-click for white, right-click for black\n self.C.bind(\"\", callback2)\n self.C.bind(\"\", callback)\n\n def resize(self, x, y):\n if x==self.dim_x and y==self.dim_y:\n return\n self.dim_x = x\n self.dim_y = y\n self.diam = (float(min(x,y))-2*float(self.margin))/float(self.spaces-1)\n self.drawGrid()\n self.drawBoard()\n \n def goForWhite(self, pi, pj):\n #tree = MinMaxTree(self.board, False, True, 0, 0.0, 'b({},{})'.format(pi,pj))\n #bestMove = tree.decideNextMove()\n \n #self.board.place_stone(bestMove.i, bestMove.j, False)\n #print(self.board)\n self.drawBoard()\n\n def mainloop(self):\n mainloop()\n\n def computeSpace(self, x_coord, y_coord):\n i = int(round((y_coord-self.margin)/self.diam))\n if( i<0 ):\n i=0\n elif( i>self.spaces-1 ):\n i = self.spaces - 1\n j = int(round((x_coord-self.margin)/self.diam))\n if( j<0 ):\n j=0\n elif( j>self.spaces-1 ):\n j = self.spaces - 1\n return [i, j]\n\n def computeCoord(self, i, j):\n y = self.margin+round((i)*self.diam)\n x = self.margin + round((j)*self.diam)\n return [x, y]\n\n def placeStoneNear(self, x, y, color):\n [i, j] = self.computeSpace(x, y)\n #print(\"test.place_stone({},{}, {})\".format(i,j, color=='black'))\n #if not self.board.board_spaces()[i][j] == '0':\n if (i,j) in self.board.white_stones+self.board.black_stones:\n print (\"There's already a stone at ({}, {}).\".format(i, j))\n else:\n self.board.place_stone(i, j, color=='black')\n #print(self.board)\n self.drawBoard()\n\n def drawStone(self, i, j, color, alive=False):\n [x0, y0] = self.computeCoord(i, j)\n x2 = x0+self.diam/2 #10\n y2 = y0+self.diam/2 #10\n x1 = x0+1-self.diam/2 #9\n y1 = y0+1-self.diam/2\n \n self.ovals.append(self.C.create_oval(x1, y1, x2, y2, fill=color, tags=color))\n if( alive ):\n self.ovals.append(self.C.create_oval(x0-2, y0-2, x0+1, y0+1, fill='green', tags=color))\n def setBoardIndex(self, index):\n self.setBoard(self.boards[int(index)])\n self.drawBoard()\n \n def showPath(self, boards):\n self.boards = boards\n scale = Scale(self.master, orient=HORIZONTAL, from_=0, to=len(boards)-1, command=self.setBoardIndex, bg='#d8af4f',highlightthickness=0)\n scale.pack(side=BOTTOM, padx=10, pady=10, expand=NO)\n self.setBoard(boards[0])\n self.drawBoard()\n self.mainloop()\n \n def drawPoint(self, i, j):\n [x0, y0] = self.computeCoord(i, j)\n x1 = x0+5\n y1 = y0+5\n x0 = x0-4\n y0 = y0-4\n self.ovals.append(self.C.create_oval(x0, y0, x1, y1, fill='black'))\n def setBoard(self, newboard):\n self.board = newboard\n\n def drawGrid(self):\n if self.C is None:\n #self.C.destroy()\n self.C = ResizingCanvas(self.master, self, width=self.dim_x, height=self.dim_y, highlightthickness=0, bg='#d8af4f')\n #self.C.grid(row=0,column=0, sticky=tkinter.N+tkinter.S+tkinter.W+tkinter.E)\n \n self.C.pack(side=TOP, fill=BOTH, expand=YES)\n self.C.delete(ALL)\n for i in range(self.spaces):\n bound = min(self.dim_x, self.dim_y)\n self.C.create_line(self.margin, self.margin+i*self.diam, bound-self.margin, self.margin+i*self.diam)\n self.C.create_line(self.margin+i*self.diam, self.margin, self.margin+i*self.diam, bound-self.margin )\n self.drawPoint(3, 3)\n self.drawPoint(3, self.spaces-4)\n self.drawPoint(self.spaces-4, 3)\n self.drawPoint(self.spaces-4, self.spaces-4)\n self.drawPoint(3, (self.spaces-1)/2)\n self.drawPoint((self.spaces-1)/2, 3)\n self.drawPoint((self.spaces-1)/2, (self.spaces-1)/2)\n self.drawPoint(self.spaces-4, (self.spaces-1)/2)\n self.drawPoint((self.spaces-1)/2, self.spaces-4)\n\n ''' Draws board dim_x x dim_y pixels, with margin 'margin'\n and number of spaces 'spaces'. Only tested with (400, 400, 12, 19).\n '''\n def drawBoard(self): #board, dim_x, dim_y, diam, margin, spaces):\n #i = 0\n for c in self.C.children:\n c.destroy()\n for [color,stones] in [['white', self.board.white_stones], ['black', self.board.black_stones]]:\n living_groups = determineLife(self.board, color)\n self.C.delete(color)\n for stone in stones:\n alive = False\n for group in living_groups:\n if not alive and stone in group:\n alive = True\n self.drawStone(stone[0],stone[1],color,alive)\n #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MARGIN, DEFAULT_SPACES)\n #ui=Launcher(DEFAULT_WIDTH, DEFAULT_HEIGHT, 30,5)\n #ui.drawBoard()\n '''\n p1 = Problem('c:/users/jblackmore/Documents/Personal/Rutgers/530/gold/dataset/9286.sgf')\n ui = Launcher(400,400,30,19)\n mmt = MinMaxTree(p1.start, True, False, 0, 0.0)\n print(\"Value={}\".format(mmt.value))\n ui.setBoard(p1.start)\n ui.drawBoard()\n ui.mainloop()\n '''\ndef load_problem_start(f):\n mtp = MoveTreeParser(f)\n return mtp.start\n\ndef load_problem_paths(f):\n mtp = MoveTreeParser(f)\n #print('{} := {}'.format(f.split('/')[-1].split('\\\\')[-1], mtp.problemType))\n sn = mtp.getSolutionNodes()\n inc = mtp.getIncorrectNodes()\n probtyp = mtp.getProblemType()\n if probtyp == 1 or probtyp == 3: #Black to live\n probtyp = 1\n elif probtyp == 2 or probtyp == 4: #White to kill\n probtyp = 2\n else: #Error should be thrown, but just in case it isn't\n probtyp = 0\n paths = mtp.getAllPaths()\n boards = []\n for path in paths:\n start = mtp.start\n if( len(path)>100 ):\n print('START NEW PATH (len={}; {})'.format(len(path),f.split('/')[-1]))\n move = None\n outcome = 0\n liveWGr = determineLife(start, False)\n liveBGr = determineLife(start, True)\n w = len(liveWGr)\n b = len(liveBGr)\n boards.append(start)\n print('START: w={}, b={}, nw={}, nb={}'.format(w,b,len(start.white_stones),len(start.black_stones)))\n for mid in path:\n move_dict = mtp.formatMove(mtp.moveID[mid])\n saysblack = move_dict['isBlack'] #move_str[0:1]=='B'\n #print('{}''s turn'.format('black' if saysblack else 'white'))\n move_y = move_dict['y'] #ord(move_str[2]) - ord('a')\n move_x = move_dict['x'] #ord(move_str[3]) - ord('a')\n move = start.clone()\n try:\n move.place_stone(move_x, move_y, saysblack)\n boards.append(move)\n color = 'B' if saysblack else 'W'\n print('{}({},{}): w={}, b={}, nw={}, nb={}'.format(color,move_x,move_y,w,b,len(move.white_stones),len(move.black_stones)))\n except IllegalMove as e:\n print('{}: ({},{})'.format(e, move_x, move_y))\n start = move\n if outcome==1: \n return move\n return boards\n\ndef load_problem_solution(f):\n mtp = MoveTreeParser(f)\n #print('{} := {}'.format(f.split('/')[-1].split('\\\\')[-1], mtp.problemType))\n sn = mtp.getSolutionNodes()\n inc = mtp.getIncorrectNodes()\n probtyp = mtp.getProblemType()\n if probtyp == 1 or probtyp == 3: #Black to live\n probtyp = 1\n elif probtyp == 2 or probtyp == 4: #White to kill\n probtyp = 2\n else: #Error should be thrown, but just in case it isn't\n probtyp = 0\n isBTL = (probtyp==1) or (probtyp==0) # and mtp.blackFirst)\n if not sn.isdisjoint(inc):\n print('NOT DISJOINT')\n paths = mtp.getAllPaths()\n movesConsidered = set()\n for path in paths:\n parent = 0\n start = mtp.start\n if( len(path)>100 ):\n print('START NEW PATH (len={}; {})'.format(len(path),f.split('/')[-1]))\n move = None\n outcome = 0\n liveWGr = determineLife(start, False)\n liveBGr = determineLife(start, True)\n w = len(liveWGr)\n b = len(liveBGr)\n print('START: w={}, b={}, nw={}, nb={}'.format(w,b,len(start.white_stones),len(start.black_stones)))\n for mid in path:\n move_dict = mtp.formatMove(mtp.moveID[mid])\n saysblack = move_dict['isBlack'] #move_str[0:1]=='B'\n #print('{}''s turn'.format('black' if saysblack else 'white'))\n move_y = move_dict['y'] #ord(move_str[2]) - ord('a')\n move_x = move_dict['x'] #ord(move_str[3]) - ord('a')\n move = start.clone()\n try:\n move.place_stone(move_x, move_y, saysblack)\n color = 'B' if saysblack else 'W'\n print('{}({},{}): w={}, b={}, nw={}, nb={}'.format(color,move_x,move_y,w,b,len(move.white_stones),len(move.black_stones)))\n if (parent, mid) not in movesConsidered:\n #features = [probtyp]\n outcome = 0\n if isBTL == saysblack:\n #CHECK THIS LOGIC\n if mid in sn:\n outcome = 1\n elif mid in inc:\n outcome = 0\n else:\n raise Exception('Unknown outcome!')\n else:\n ''' Assume only moves on incorrect path are correct\n for the \"antagonist\" '''\n if mid in inc:\n outcome = 1\n ''' Assume all moves for the \"antagonist\" are correct '''\n # outcome = 1\n movesConsidered.add((parent, mid))\n #vectors.append(features)\n # Only train on the first wrong move for the protagonist\n if outcome==0 and isBTL==saysblack:\n break;\n except IllegalMove as e:\n print('{}: ({},{})'.format(e, move_x, move_y))\n parent = mid\n start = move\n if outcome==1: \n return move\n return None\n\nif __name__ == '__main__':\n print(\"Starting GoLD...\")\n if len(sys.argv)>1:\n #solution = load_problem_start(sys.argv[1])\n paths = load_problem_paths(sys.argv[1])\n ui = Launcher(400,400,50,19,board=paths[0])\n ui.showPath(paths)\n else:\n ui = Launcher(400,400,50,19)\n ui.drawBoard()\n ui.mainloop()\n","sub_path":"src/gold/ui/Launcher.py","file_name":"Launcher.py","file_ext":"py","file_size_in_byte":12882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"322632420","text":"import sys\nfrom util import *\nimport json\nimport numpy as np\n\n\ndef main(argv):\n path = \"../data/pn_analysis/\"\n file_list = [\"predict_2_2\", \"predict_0_4\", \"predict_2_6\", \"predict_4_8\"]\n\n r2_list = []\n coef_list = []\n p_list = []\n for i in range(6):\n r2_list.append([])\n coef_list.append([])\n p_list.append([])\n for f in file_list:\n lines = loadText(path + f + \".txt\")\n for i in range(len(lines)):\n line = lines[i]\n if i in [6, 25]:\n m = 0\n elif i in [7, 28]:\n m = 1\n elif i in [9, 33]:\n m = 2\n elif i in [10, 36]:\n m = 3\n elif i in [12, 41]:\n m = 4\n elif i in [13, 44]:\n m = 5\n # M1, M2, M3, M4, M5, M6\n if i in [6, 7, 9, 10, 12, 13]:\n s = line.split(\"&\")\n before = s[1].strip().split(\"$\")[0].strip()\n after = s[2].strip().split(\"$\")[0].strip()\n diff = float(after) - float(before)\n # M1, M2, M3, M4, M5, M6\n if i in [25, 28, 33, 36, 41, 44]:\n s = line.split(\"&\")\n r2 = s[4].strip()\n if \"textbf\" in r2:\n r2 = r2[8:-1]\n r2 = float(\"0\" + r2)\n r2_list[m].append(r2)\n if \"n/a\" in s[5]:\n coef = 0\n else:\n coef = s[5].strip()\n coef = float(coef)\n coef_list[m].append(coef)\n if \"n/a\" in s[7]:\n p = 0\n else:\n p = s[7].strip()\n if \"textbf\" in p:\n if \"<\" in p:\n p = 2 # p<.001\n else:\n p = 1 # p<.05\n else:\n p = 0 # not significant or not selected\n p_list[m].append(p)\n print(r2_list)\n print(coef_list)\n print(p_list)\n\n metric_name = [\"# of smell reports\", \"# of unique users in reports\", \"# of unique zipcodes in reports\",\n \"# of Google Analytics events\", \"# of unique users in events\", \"# of pageviews\"]\n # Plot\n w = 3\n h = 2\n w_size = 4\n h_size = 1.7\n sup_title_font_size = 18\n title_font_size = 14\n label_font_size = 10\n top = 0.83\n hspace = 0.6\n wspace = 0.25\n xticks = [\"0-2h\", \"2-4h\", \"4-6h\", \"6-8h\"]\n\n fig = plt.figure(figsize=(w_size*w, h_size*h+1))\n plt.suptitle(\"R-squared of type P1 notification over time (second sub-study)\", fontsize=sup_title_font_size)\n for i in range(len(r2_list)):\n ax = plt.subplot(h, w, i+1)\n d = r2_list[i]\n ax.plot(np.array(range(len(d))), d, \"o-\")\n ax.set_title(metric_name[i], fontsize=title_font_size)\n #ax.set_xlabel(\"Hour\", fontsize=label_font_size)\n plt.xticks(range(len(xticks)), xticks)\n ax.set_ylabel(\"R-squared\", fontsize=label_font_size)\n ax.set_ylim([0.4,1])\n plt.tight_layout()\n fig.subplots_adjust(top=top, hspace=hspace, wspace=wspace)\n fig.savefig(path + \"r2_predict_hours.png\", dpi=150)\n fig.clf()\n plt.close()\n\n fig = plt.figure(figsize=(w_size*w, h_size*h+1))\n plt.suptitle(\"Coefficient of type P1 notification over time (second sub-study)\", fontsize=sup_title_font_size)\n for i in range(len(r2_list)):\n ax = plt.subplot(h, w, i+1)\n d = coef_list[i]\n ax.plot(np.array(range(len(d))), np.exp(d), \"o-\")\n ax.set_title(metric_name[i], fontsize=title_font_size)\n #ax.set_xlabel(\"Hour\", fontsize=label_font_size)\n plt.xticks(range(len(xticks)), xticks)\n ax.set_ylabel(\"Exponential of coef\", fontsize=label_font_size)\n ax.set_ylim([1,4])\n plt.tight_layout()\n fig.subplots_adjust(top=top, hspace=hspace, wspace=wspace)\n fig.savefig(path + \"coef_predict_hours.png\", dpi=150)\n fig.clf()\n plt.close()\n\n fig = plt.figure(figsize=(w_size*w, h_size*h+1))\n plt.suptitle(\"Significance of type P1 notification over time (second sub-study)\", fontsize=sup_title_font_size)\n for i in range(len(r2_list)):\n ax = plt.subplot(h, w, i+1)\n d = p_list[i]\n ax.plot(np.array(range(len(d))), d, \"o-\")\n ax.set_title(metric_name[i], fontsize=title_font_size)\n #ax.set_xlabel(\"Hour\", fontsize=label_font_size)\n plt.xticks(range(len(xticks)), xticks)\n ax.set_ylabel(\"Significance\", fontsize=label_font_size)\n plt.yticks(range(3), [\">=.05\", \"<.05\", \"<.001\"])\n ax.set_ylim([-0.1,2.1])\n plt.tight_layout()\n fig.subplots_adjust(top=top, hspace=hspace, wspace=wspace+0.05)\n fig.savefig(path + \"p_predict_hours.png\", dpi=150)\n fig.clf()\n plt.close()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"py/plotRegressionAnalysis.py","file_name":"plotRegressionAnalysis.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"492314479","text":"#!/usr/bin/env python\n# *-* coding: UTF-8 *-*\n\n# Copyright 2012-2022 Ronald Römer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.extend(['/home/zippy/vtkbool/build/lib/python3.10/site-packages/vtkbool'])\n\nfrom vtkmodules.vtkIOLegacy import vtkPolyDataReader, vtkPolyDataWriter\nfrom vtkBool import vtkPolyDataBooleanFilter\n\nreaderA = vtkPolyDataReader()\nreaderA.SetFileName('AnteriorToInferiorModelSequence.vtk')\n\nreaderB = vtkPolyDataReader()\nreaderB.SetFileName('InferiorAir.vtk')\n\nbf = vtkPolyDataBooleanFilter()\nbf.SetInputConnection(0, readerA.GetOutputPort())\nbf.SetInputConnection(1, readerB.GetOutputPort())\nbf.SetOperModeToNone()\n\n# das ursprüngliche problem war bei cell 151227\n\nwriter0 = vtkPolyDataWriter()\nwriter0.SetFileName('result0.vtk')\nwriter0.SetInputConnection(bf.GetOutputPort())\nwriter0.Update()\n\nwriter1 = vtkPolyDataWriter()\nwriter1.SetFileName('result1.vtk')\nwriter1.SetInputConnection(bf.GetOutputPort(1))\nwriter1.Update()\n\nwriter2 = vtkPolyDataWriter()\nwriter2.SetFileName('lines.vtk')\nwriter2.SetInputConnection(bf.GetOutputPort(2))\nwriter2.Update()\n\n# fehler bei 544,545,546,547,548,690,691,692,693\n# sind lines in holes\n","sub_path":"testing/_test/_test.py","file_name":"_test.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"453069570","text":"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\r\n\r\nLer 5 valores e, em seguida, mostrar a posição \r\nonde se encontra o maio e o menor valor\r\n\r\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'\r\n\r\nlista = []\r\nfor i in range(1,6):\r\n number = lista.append(int(input(f\"Insira o {i} item da lista\")))\r\nprint(lista)\r\n\r\nvalor = max(lista)\r\nposicao = lista.index(valor)\r\nprint(\"o valor maximo\", valor, \"a posição\", posicao)\r\n","sub_path":"funcoes/lista13.py","file_name":"lista13.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651276715","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\n\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.shortcuts import render_to_response,RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom automation.common.CommonPaginator import SelfPaginator\nfrom auto_auth.views.permission import PermissionVerify\n\nfrom auto_auth.forms import RoleGroupForm\nfrom auto_auth.models import RoleGroup\n\n@login_required\n@PermissionVerify()\ndef AddRole(request):\n#添加url权限\n if request.method == \"POST\":\n form = RoleGroupForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('listroleurl'))\n else:\n form = RoleGroupForm()\n\n kwvars = {\n 'form':form,\n 'request':request,\n }\n\n return render_to_response('auto_auth/role.add.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef ListRole(request):\n#列出url权限\n mList = RoleGroup.objects.all()\n\n #分页功能\n lst = SelfPaginator(request,mList, 20)\n\n kwvars = {\n 'lPage':lst,\n 'request':request,\n }\n\n return render_to_response('auto_auth/role.list.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef EditRole(request,ID):\n#编辑url权限\n iRole = RoleGroup.objects.get(id=ID)\n\n if request.method == \"POST\":\n form = RoleGroupForm(request.POST,instance=iRole)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('listroleurl'))\n else:\n form = RoleGroupForm(instance=iRole)\n\n kwvars = {\n 'ID':ID,\n 'form':form,\n 'request':request,\n }\n\n return render_to_response('auto_auth/role.edit.html',kwvars,RequestContext(request))\n\n@login_required\n@PermissionVerify()\ndef DeleteRole(request,ID):\n#删除url权限\n RoleGroup.objects.filter(id = ID).delete()\n\n return HttpResponseRedirect(reverse('listroleurl'))\n","sub_path":"auto_auth/views/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"56827555","text":"import requests\nimport json\nimport re\nimport time\nimport functools\nfrom bs4 import BeautifulSoup\n\n# url = \"https://www.4cc1cb1f9661.com/xiazai/list-%E4%BA%9A%E6%B4%B2%E7%94%B5%E5%BD%B1-{}.html\"\nurl = 'https://www.15edc708571e.com/shipin/list-%E4%B8%AD%E6%96%87%E5%AD%97%E5%B9%95-{}.html'\n\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3724.8 Safari/537.36'}\n\ntry:\n allData = json.load(open(\"index.json\", \"r\", encoding='utf-8'))\nexcept:\n allData = []\nprint(\"当前数量:{}\".format(len(allData)))\ndata_filter = []\n\n\ndef fun_filter(obj):\n if obj['id'] in data_filter:\n return False\n else:\n data_filter.append(obj['id'])\n return True\n\ndef cmp(obj_a, obj_b):\n time_a = time.mktime(time.strptime(obj_a['date'], \"%Y-%m-%d\"))\n time_b = time.mktime(time.strptime(obj_b['date'], \"%Y-%m-%d\"))\n return time_b - time_a\n\ndef del_null(str):\n return re.sub(r\"[\\s/]\", '', str)\n\n\nfor page in range(1, 85):\n print(\"正在爬取第 {} 页\".format(page))\n html_doc = requests.get(url.format(page), headers=HEADERS).content.decode('utf-8')\n soup = BeautifulSoup(html_doc, 'lxml')\n\n infoList = soup.select('#tpl-img-content .tupian-pic')\n dataList = soup.select('#tpl-img-content .down_date')\n for index in range(len(infoList)):\n item = {}\n item['id'] = infoList[index].get('href')\n item['title'] = infoList[index].get('title')\n item['date'] = del_null(dataList[index].get_text())\n allData.append(item)\n\n\nallData = list(filter(fun_filter, allData))\nallData.sort(key=functools.cmp_to_key(cmp))\nprint(\"当前数量:{}\".format(len(allData)))\njson.dump(allData, open(\"index.json\", \"w\", encoding='utf-8'), ensure_ascii=False)\n","sub_path":"yl_python_code/MY_spider/爬虫代码/小实战/kitty/02/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"104439349","text":"\"\"\"code mostly adapted from\nhttps://code.likeagirl.io/finding-dominant-colour-on-an-image-b4e075f98097\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n\ndef find_histogram(clt):\n \"\"\"\n create a histogram with k clusters\n :param: clt\n :return:hist\n \"\"\"\n numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)\n (hist, _) = np.histogram(clt.labels_, bins=numLabels)\n\n hist = hist.astype(\"float\")\n hist /= hist.sum()\n\n return hist\ndef plot_colors2(hist, centroids):\n bar = np.zeros((50, 300, 3), dtype=\"uint8\")\n startX = 0\n\n for (percent, color) in zip(hist, centroids):\n # plot the relative percentage of each cluster\n endX = startX + (percent * 300)\n cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),\n color.astype(\"uint8\").tolist(), -1)\n startX = endX\n\n # return the bar chart\n return bar\n \ndef main():\n cap = cv2.VideoCapture(0)\n while(1):\n _, frame = cap.read()\n frame = frame[200:400, 200:400]\n #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n rframe = frame.reshape((frame.shape[0] * frame.shape[1],3)) #represent as row*column,channel number\n clt = KMeans(n_clusters=3) #cluster number\n clt.fit(rframe)\n\n hist = find_histogram(clt)\n bar = plot_colors2(hist, clt.cluster_centers_)\n\n #add rectangle in the middle\n cv2.rectangle(frame, (200,200), (400,400), (255,0,0))\n cv2.imshow(\"hist\", bar)\n cv2.imshow(\"frame\", frame)\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n \nif __name__ == \"__main__\":\n main()\n cv2.destroyAllWindows()","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"341801506","text":"def bil_prim(x,y):\n for bil in range(x,y):\n prima = True\n if bil > 1:\n for j in range (2,bil):\n if (bil%j==0):\n break\n else:\n print(bil)\n\nprint(\"Bilangan prima antara 1 dan 100 : \")\nbil_prim(1,100)","sub_path":"CodeJo Python/Alza/Loop Bilangan Prima.py","file_name":"Loop Bilangan Prima.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"568347070","text":"import os\nimport filetype\nclass BaseFileUploader():\n def __init__(self, dir, s3_connector, s3_bucket_name, s3_format_filter=[]):\n self.dir = dir\n self.s3 = s3_connector\n self.s3_format_filter = s3_format_filter\n self.s3_bucket = s3_bucket_name\n self.checkS3BucketConnection()\n\n def checkS3BucketConnection(self):\n return self.s3.Bucket(self.s3_bucket).creation_date != None\n\n def readAll(self):\n for root, directories, files in os.walk(self.dir, topdown=False):\n for name in files:\n try:\n file_type = self.getFileType(os.path.join(root, name))\n if file_type in self.s3_format_filter:\n self.upload_s3(os.path.join(root, name), name)\n except Exception as e:\n print(\"Failed to upload %s with the below error.\"%(os.path.join(root, name)))\n print(e)\n\n def getFileType(self, path):\n # print(path)\n kind = filetype.guess(path)\n return kind.mime\n\n def upload_s3(self, path, filename):\n print(\"Uploading : %s\"%(filename))\n self.s3.Bucket(self.s3_bucket).upload_file(Filename=path, Key=filename)\n print(\"Uploaded : %s\"%(filename))\n","sub_path":"reader/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"15395027","text":"from bge import logic\npath = logic.expandPath(\"//levels/\")\n\ndef save():\n cont = logic.getCurrentController()\n own = cont.owner \n # 'info' is what will be saved to the file.\n # Example:\n # info = str(*What you want to save*)\n \n info = str(own['score']) + \" , \" + str(own['L1']) + \" , \" + str(own['L2']) + \" , \" + str(own['L3']) + \" , \" + str(own['L4']) + \" , \" + str(own['L5']) + \" , \" + str(own['L6']) + \" , \" + str(own['L7']) + \" , \" + str(own['L8']) + \" , \" + str(own['L9']) + \" , \" + str(own['L10']) + \" , \" + str(own['L11']) + \" , \" + str(own['L12']) + \" , \" + str(own['L13']) + \" , \" + str(own['L14']) + \" , \" + str(own['L15']) + \" , \" + str(own['L16']) + \" , \" + str(own['L17']) + \" , \" + str(own['L18']) + \" , \" + str(own['L19']) + \" , \" + str(own['L20']) + \" , \" + str(own['L21']) + \" , \" + str(own['L22']) + \" , \" + str(own['L23']) + \" , \" + str(own['L24']) + \" , \" + str(own['L25']) + \" , \" + str(own['L26']) + \" , \" + str(own['L27']) + \" , \" + str(own['L28']) + \" , \" + str(own['L29']) + \" , \" + str(own['L30']) + \" , \" + str(own['L31']) + \" , \" + str(own['L32']) + \" , \" + str(own['L33']) + \" , \" + str(own['L34']) + \" , \" + str(own['L35'])\n \n file = open(path+\".#scorekeep1empty1.txt\", 'w') \n file.write(str(info))\n \ndef load():\n cont = logic.getCurrentController()\n own = cont.owner\n \n file = open(path+'.#scorekeep1empty1.txt','r')\n line = file.readline().replace('\\n','').split(',')\n own['score'] = int(line[0])\n own['L1'] = int(line[1])\n own['L2'] = int(line[2])\n own['L3'] = int(line[3])\n own['L4'] = int(line[4])\n own['L5'] = int(line[1])\n own['L6'] = int(line[2])\n own['L7'] = int(line[3])\n own['L8'] = int(line[4])\n own['L9'] = int(line[1])\n own['L10'] = int(line[2])\n own['L11'] = int(line[3])\n own['L12'] = int(line[4])\n own['L13'] = int(line[1])\n own['L14'] = int(line[2])\n own['L15'] = int(line[3])\n own['L16'] = int(line[4])\n own['L17'] = int(line[1])\n own['L18'] = int(line[2])\n own['L19'] = int(line[3])\n own['L20'] = int(line[4])\n own['L21'] = int(line[1])\n own['L22'] = int(line[2])\n own['L23'] = int(line[3])\n own['L24'] = int(line[4])\n own['L25'] = int(line[1])\n own['L26'] = int(line[2])\n own['L27'] = int(line[3])\n own['L28'] = int(line[4])\n own['L29'] = int(line[1])\n own['L30'] = int(line[2])\n own['L31'] = int(line[3])\n own['L32'] = int(line[4])\n own['L33'] = int(line[1])\n own['L34'] = int(line[2])\n own['L35'] = int(line[3])","sub_path":"BA Kit v1 Group Link Testing/scripts/SaveLoadMain.py","file_name":"SaveLoadMain.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"455263561","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\n\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n \n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n def forward(self, images):\n features = self.resnet(images)\n features = features.view(features.size(0), -1)\n features = self.embed(features)\n return features\n \n\nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super(DecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed_size)\n self.lstm = nn.LSTM(input_size=embed_size, hidden_size=hidden_size, num_layers=num_layers, \n batch_first=True, dropout=0.3)\n self.linear = nn.Linear(in_features=hidden_size, out_features=vocab_size)\n self.init()\n \n \n def init(self):\n torch.nn.init.kaiming_uniform_(self.embedding.weight)\n torch.nn.init.kaiming_uniform_(self.linear.weight)\n \n \n def forward(self, features, captions):\n captions = captions[:,:-1]\n captions = self.embedding(captions)\n \n features = features.unsqueeze(1)\n inputs = torch.cat((features, captions), 1)\n out, hidden = self.lstm(inputs)\n out = self.linear(out)\n return out\n \n\n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n caption = []\n stopword_idx = 1\n for i in range(max_len):\n out, states = self.lstm(inputs, states)\n out = self.linear(out) # shape is (batch_size, seq_len, vocab_size)\n word = out.argmax(dim=-1)\n caption.append(word.item())\n inputs = self.embedding(word)\n if word == stopword_idx:\n break\n return caption","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"450801396","text":"from django.urls import path\nfrom .views import ArticleAPIView, ArticleDetails, GenericAPIView, GetSpecificAuthor, GetSpecificAuthorUnread\nurlpatterns = [\n path('all_message/', ArticleAPIView.as_view()),\n path('message//', ArticleDetails.as_view()),\n path('new_message/', ArticleAPIView.as_view()),\n path('message//delete', GenericAPIView.as_view()),\n path('get_specific_user//', GetSpecificAuthor.as_view()),\n path('get_specific_user_unread///', GetSpecificAuthorUnread.as_view()),\n\n]","sub_path":"interview-herolo/MyProject/api_basic/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"634072234","text":"beginningOdometerReading = int(input(\"Please enter the beginning odometer reading: \"))\r\nendingOdometerReading = int(input(\"Please enter the ending odometer reading: \"))\r\ngallonsToFillTank = float(input(\"Please enter the number of gallons to fill the tank: \"))\r\ncostPerGallonOfGas = float(input(\"Please enter the cost per gallon of fuel: \"))\r\nnumberMilesDrivenPerYear = int(input(\"Please enter the number of miles driven per year: \"))\r\n\r\ntotalMilesDriven = endingOdometerReading - beginningOdometerReading\r\naverageMilesPerGallon = totalMilesDriven / gallonsToFillTank\r\n\r\ncostOfGas = gallonsToFillTank * costPerGallonOfGas\r\nfuelCostPerMile = costOfGas/totalMilesDriven\r\n\r\nannualCostOfFuel = (numberMilesDrivenPerYear/averageMilesPerGallon) * costPerGallonOfGas\r\n\r\nprint(\"Average Miles Per Gallon:\",format(averageMilesPerGallon, \"<2.2f\"))\r\nprint(\"Fuel Cost Per Mile:\", '${:,.2f}'.format(fuelCostPerMile))\r\nprint(\"Annual Cost of Fuel:\", '${:,.2f}'.format(annualCostOfFuel))\r\n","sub_path":"Assignment 2/PS2_Part3.py","file_name":"PS2_Part3.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616637862","text":"import os\nimport sys\nimport argparse\nfrom Bio import SeqIO\n\n########### ARGUMENTS ###########\nparser = argparse.ArgumentParser(description='XXX')\n\nparser.add_argument('-a', '--proteinA',\n help = \"First protein fasta file\",\n required = True)\n\nparser.add_argument('-b', '--proteinB',\n help = \"First protein fasta file\",\n required = True)\n\nparser.add_argument('-l', '--length',\n help=\"Minimum homology length\",\n default = 0.5)\n\nparser.add_argument('-e', '--eval',\n help=\"Minimum e-value\",\n default = 1e-15)\n\nparser.add_argument('-i', '--percentID',\n help=\"Minimum percent identity\",\n default = 0.5)\n\nargs = parser.parse_args()\nargs.length = float(args.length)\nargs.eval = float(args.eval)\nargs.percentID = float(args.percentID)\nif args.percentID < 1: # blast gives as percentage rather than ratio\n args.percentID = args.percentID * 100\n\n########### Process File A ###########\n\nos.system('formatdb -i '+args.proteinA+' -o T -p T')\naDict = {}\nfor seq_record in SeqIO.parse(args.proteinA, \"fasta\"):\n seq_record.seq = seq_record.seq.rstrip(\"*\")\n aDict[seq_record.id] = {'length' : len(seq_record.seq), \"hit\" : \"\", \"percentLength\" : 0, \"eval\" : 1, \"percentID\" : 0, \"reciprocal\" : 0}\n\n########### Process File B ###########\n\nos.system('formatdb -i '+args.proteinB+' -o T -p T')\nbDict = {}\nfor seq_record in SeqIO.parse(args.proteinB, \"fasta\"):\n seq_record.seq = seq_record.seq.rstrip(\"*\")\n bDict[seq_record.id] = {'length' : len(seq_record.seq), \"hit\" : \"\", \"percentLength\" : 0, \"eval\" : 1, \"percentID\" : 0, \"reciprocal\" : 0}\n\n########### RUN BLASTs ###########\n\nos.system('blastall -p blastp -i '+args.proteinA+' -d '+args.proteinB+' -m 8 -e 1e-7 -o a_against_b.blastp')\nos.system('blastall -p blastp -d '+args.proteinA+' -i '+args.proteinB+' -m 8 -e 1e-7 -o b_against_a.blastp')\n\n########### PROCESS BLASTs ###########\n\nfor line in open('a_against_b.blastp', 'rt'):\n line = line.rstrip()\n [query, subject, percent_id, alignment_length, mismatches, gap_openings, query_start, query_end, subject_start, subject_end, E_value, bit_score] = line.split(\"\\t\")\n\n # add hits satisfying criteria to dictionary\n percentLength = int(alignment_length) / aDict[query]['length']\n if percentLength >= args.length:\n if float(E_value) <= args.eval:\n if float(percent_id) >= args.percentID:\n if percentLength >= aDict[query]['percentLength']:\n if float(E_value) <= aDict[query]['eval']:\n aDict[query]['hit'] = subject\n aDict[query]['percentLength'] = percentLength\n aDict[query]['alignLength'] = int(alignment_length)\n aDict[query]['eval'] = float(E_value)\n aDict[query]['percentID'] = float(percent_id)\n\nfor line in open('b_against_a.blastp', 'rt'):\n line = line.rstrip()\n [query, subject, percent_id, alignment_length, mismatches, gap_openings, query_start, query_end, subject_start, subject_end, E_value, bit_score] = line.split(\"\\t\")\n\n # add hits satisfying criteria to dictionary\n percentLength = int(alignment_length) / bDict[query]['length']\n if percentLength >= args.length:\n if float(E_value) <= args.eval:\n if float(percent_id) >= args.percentID:\n if percentLength >= bDict[query]['percentLength']:\n if float(E_value) <= bDict[query]['eval']:\n bDict[query]['hit'] = subject\n bDict[query]['percentLength'] = percentLength\n bDict[query]['alignLength'] = int(alignment_length)\n bDict[query]['eval'] = float(E_value)\n bDict[query]['percentID'] = float(percent_id)\n\n########### FIND RECIPROCAL HITS ###########\n\nfor query in aDict:\n subject = aDict[query]['hit']\n if subject != \"\":\n if query == bDict[subject]['hit']:\n aDict[query]['reciprocal'] = 1\n bDict[subject]['reciprocal'] = 1\n\nfor query in sorted(aDict.keys()):\n if aDict[query]['reciprocal'] == 1:\n subject = aDict[query]['hit']\n print(query, aDict[query]['length'], aDict[query]['alignLength'], aDict[query]['percentID'], aDict[query]['eval'], sep = \"\\t\", end = \"\\t\")\n print(subject, bDict[subject]['length'], bDict[subject]['alignLength'], bDict[subject]['percentID'], bDict[subject]['eval'], sep = \"\\t\")\n else:\n print(query, \"-\", \"-\", \"-\", \"-\", \"None\", \"-\", \"-\", \"-\", \"-\", sep = \"\\t\")\n\nfor query in sorted(bDict.keys()):\n if bDict[query]['reciprocal'] != 1:\n print(\"None\", \"-\", \"-\", \"-\", \"-\", query, \"-\", \"-\", \"-\", \"-\", sep = \"\\t\")\n","sub_path":"fasta/reciprocalBestBlast.py","file_name":"reciprocalBestBlast.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394925435","text":"import json\nfrom .. import define\nfrom .. import interface\nfrom .. import mm_pb2\nfrom .. import Util\nfrom . import plugin\nfrom bs4 import BeautifulSoup\nfrom .logger_wrapper import logger\n\n\n# appmsg 消息处理\ndef appmsg_handler(msg):\n # 读取消息类型\n try:\n soup = BeautifulSoup(msg.raw.content,'html.parser')\n msg_type = soup.appmsg.type.contents[0] # 红包:\n except:\n pass\n\n if '2001' == msg_type: # 红包消息\n if plugin.TEST_STATE[4]: # 自动抢红包功能开关\n auto_recive_hb(msg) # 自动抢红包\n return\n\n\n# 自动抢红包\ndef auto_recive_hb(msg):\n try:\n # 解析nativeUrl,获取msgType,channelId,sendId\n soup = BeautifulSoup(msg.raw.content,'html.parser')\n nativeUrl = soup.msg.appmsg.wcpayinfo.nativeurl.contents[0]\n msgType = Util.find_str(nativeUrl,'msgtype=','&')\n channelId = Util.find_str(nativeUrl,'&channelid=','&')\n sendId = Util.find_str(nativeUrl,'&sendid=','&')\n\n # 领红包\n (ret_code,info) = interface.receive_and_open_wxhb(channelId,msgType,nativeUrl,sendId)\n if not ret_code:\n logger.info('自动抢红包成功!')\n logger.debug('红包详细信息:' + info)\n except:\n logger.info('自动抢红包失败!')\n return","sub_path":"microchat/plugin/handle_appmsg.py","file_name":"handle_appmsg.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"448908734","text":"from django.db.models.signals import post_save\r\nfrom django.dispatch import receiver\r\nfrom core.models import Version\r\nfrom localgaap.models import Transaction\r\nfrom localgaap.models import Setting\r\n\r\n\r\n@receiver(post_save, sender=Version, dispatch_uid=\"copy_values_from_version\")\r\ndef copy_values_from_version(sender, **kwargs):\r\n \"\"\"\r\n Signal Handler to be triggered if new Version Object is created\r\n AND created instance's copy_version property is not None\r\n Copying values from\r\n - Transactions\r\n - Settings (or create default)\r\n \"\"\"\r\n version = kwargs[\"instance\"]\r\n if kwargs[\"created\"]:\r\n if version.copy_version:\r\n # Copy Transactions\r\n values = Transaction.objects.filter(version_id=version.copy_version)\r\n for transaction in values:\r\n transaction.id = None\r\n transaction.version_id = version.id\r\n Transaction.objects.bulk_create(values)\r\n\r\n # Copy Settings\r\n setting = Setting.objects.filter(version_id=version.copy_version)[0]\r\n setting.id = None\r\n setting.version_id = version.id\r\n setting.save()\r\n else:\r\n # Store default Setting\r\n setting = Setting(version_id = version.id)\r\n setting.save()\r\n","sub_path":"localgaap/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"36838413","text":"import xarray as xr\nimport sys\nimport os\nimport glob\nfrom pathlib import Path\nimport numpy as np\n\n\"\"\"\nAdd the calculated difference in all necessary variables to the boundary condition (lbfd) files for one year. This should be run on a cluster. This script will only work when data for all year is present!\n\nInput:\n\tyear (comandline argument): The year for which the boundary files should be adapted. The year refers to the year in the original output from int2lm.\n\tlbfdpath: path to directory where boundary files are saved\n\tchangeyears: amount of years to be added to timestamp of data\n\toutputpath: path to put the adapted bondary files\n\tDiffspath: Where to find the changes (climate change deltas) to add to the boundary files. This is the ouput of earlier scripts in this repository (i.e. T00000.nc, T00001.nc etc.).\n\tdifftimesteps: Amount of timesteps (or boundary data fields) in one year\n vcflat: Altitude where the vertical coordinate levels in CCLM become flat (this can be found in runscripts or YUSPECIF). We assume a Gal-Chen vertical coordinate here.is needed for the adaptation of humidity.\n terrainpath: Path to a netcdf file containing the height of the terrain in the cosmo domain (could be a constant file such as lffd1969120100c.nc)\n height_flat: Array of the geometrical altitude of all model levels in the cclm doman (can be found e.g. in YUSPECIF file). One value for each vertical level (this means there should normally be no level 0)! \n\n\nOutput:\n\tFor every boundary file in the inputdata, a corresponding output field will be written to the path specified as outputpath.\n\"\"\"\n\nyear = int(sys.argv[1]) \n#The year (in original data) which should be processed should be passed as command line argument\nlbfdpath = f'/scratch/snx3000/robro/int2lm/HadGEM/driving_historical/{year}/'\n\nchangeyears = 100\nnewyear = year + changeyears\noutputpath = f'/scratch/snx3000/robro/int2lm/HadGEM/PGW_TEST/{newyear}/'\n\nDiffspath = '/scratch/snx3000/robro/pgwtemp/interpolated/'\ndifftimesteps = 360 * 4\n\n#options for adaptation of humidity\nvcflat=11430. \nterrainpath='/store/c2sm/ch4/robro/surrogate_input/lffd1969120100c.nc'\n\n\n\nheight_flat=np.asanyarray([22700.0, 20800.0000, 19100.0, 17550.0, 16150.0, 14900.0, 13800.0, 12785.0, 11875.0, 11020.0, 10205.0, 9440.0, 8710.0, 8015.0, 7355.0, 6725.0, 6130.0, 5565.0, 5035.0, 4530.0, 4060.0, 3615.0, 3200.0, 2815.0, 2455.0, 2125.0, 1820.0, 1545.0, 1295.0, 1070.0, 870.0, 695.0, 542.0, 412.0, 303.0, 214.0, 143.0, 89.0, 49.0, 20.0])\n\nif len(sys.argv)>5:\n\tyear=int(sys.argv[1])\n\tlbfdpath=str(sys.argv[2])\n\tlbfdpath = f'{lbfdpath}/{year}/'\n\tchangeyears = 100\n\tnewyear = year + changeyears\n\toutputpath=str(sys.argv[3])\n\toutputpath=f'{outputpath}/{newyear}/'\n\tDiffspath=str(sys.argv[4])\n\tterrainpath=str(sys.argv[5])\n\n\n\nif os.path.exists('heights.txt'):\n\theight_flat=np.genfromtxt('heights.txt',skip_header=1)[:-1,1]\n\n\n#get reference pressure function\ndef getpref(vcflat, terrainpath, height_flat):\n\tsmoothing = (vcflat - height_flat) / vcflat\n\tsmoothing = np.where(smoothing > 0, smoothing, 0)\n\n\tconst = xr.open_dataset(terrainpath)\n\thsurf = const['HSURF'].squeeze()\n\n\t#the height at which the reference pressure needs to be computed needs to be derived form the terrain following coordinates:\n\tnewheights = np.zeros((len(height_flat), hsurf.shape[0], hsurf.shape[1]))\n\n\t#add the surface height but respect the terrain following coordinates\n\tfor x in range(hsurf.shape[0]):\n\t\tfor y in range(hsurf.shape[1]):\n\t\t\tnewheights[:,x,y] = height_flat + hsurf[x,y].values * smoothing\n\n\tpref = 100000*np.exp(-(9.80665*0.0289644*newheights/(8.31447*288.15)))\n\tpref_sfc = 100000*np.exp(-(9.80665*0.0289644*hsurf.data/(8.31447*288.15)))\n\t\n\treturn pref, pref_sfc\n\n\n#function to adapt all lbfd files:\ndef lbfdadapt(lbfdpath, outputpath, Diffspath, difftimesteps, changeyears, pref, pref_sfc):\n \n\t#function to add all variables but humidity to the boundary field (use given timestep)\n\tdef diffadd(var, num, lbfd):\n\t\tDiff = xr.open_dataset(f'{Diffspath}/{var}{num:05d}.nc')[var]\n\t\tlbfd[var].data = lbfd[var].data + Diff.data.astype('float32')\n\n\t#function to calculate relative humidity\n\tdef comprelhums(lbfd, pref, pref_sfc):\n\t\tp = lbfd['PP'] + pref\n\t\tQV = lbfd['QV']\n\t\tT = lbfd['T']\n\t\t\n\t\tp_sfc = lbfd['PP'][:,-1,:,:] + pref_sfc\n\t\tQV_S = lbfd['QV_S']\n\t\tT_S = lbfd['T_S']\n\n\t\tRH = 0.263 * p * QV *(np.exp(17.67*(T - 273.15)/(T-29.65)))**(-1)\n\t\tRH_S = 0.263 * p_sfc * QV_S *(np.exp(17.67*(T_S - 273.15)/(T_S-29.65)))**(-1)\n\n\t\treturn RH, RH_S\n\n\n\t#compute new humidity funcion once temperature and pressure were changed\n\tdef computeQVnew(lbfd, num, RH_old, RH_S_old):\n\t\tDiffrh = xr.open_dataset(f'{Diffspath}/RELHUM{num:05d}.nc')['RELHUM']\n\t\tDiffrh_s = xr.open_dataset(f'{Diffspath}/RELHUM_S{num:05d}.nc')['RELHUM_S']\n\n\t\tnewRH = RH_old.data + Diffrh.data.astype('float32')\n\t\tnewRH_S = RH_S_old.data + Diffrh_s.data.astype('float32')\n\n\t\tp = lbfd['PP'] + pref\n\t\tT = lbfd['T']\n\t\tp_sfc = lbfd['PP'][:,-1,:,:] + pref_sfc\n\t\tT_S = lbfd['T_S']\n\n\t\tnewQV = (newRH.data * np.exp(17.67*(T.data - 273.15)/(T.data -29.65))) / ( 0.263 * p.data)\n\t\tnewQV_S = (newRH_S.data * np.exp(17.67*(T_S.data - 273.15)/(T_S.data -29.65))) / ( 0.263 * p_sfc.data)\n\n\t\tlbfd['QV'].data = newQV.astype('float32')\n\t\tlbfd['QV_S'].data = newQV_S.astype('float32')\n\n\t\treturn lbfd\n\n\n\n\t# calculation part\n\t#get a list of all lbfd files:\n\tos.chdir(lbfdpath)\n\tfiles = glob.glob('lbfd??????????.nc')\n\tfiles.sort()\n\n\t#if output directory doesn't exist create it\n\tPath(outputpath).mkdir(parents=True, exist_ok=True)\n\n\t#loop over all boundary fields:\n\tfor num,lbfdnum in enumerate(files):\n\t\t#print and open boundary data\n\t\tprint(num, lbfdnum)\n\t\tlbfd = xr.open_dataset(lbfdnum, decode_cf=False)\n\n\t\t#if there is a file for the next year in the folder use first timestep; print to check\n\t\tif num >= difftimesteps:\n\t\t\tnum = 0\n\t\t\tprint(f'used first delta for {lbfdnum}')\n\t\t\n\n\t\t#run the defined functions and change filename & time:\n\t\tRH_old, RH_S_old = comprelhums(lbfd, pref, pref_sfc)\n\n\t\tvariables = ['T', 'T_S', 'U', 'V']\n\n\t\tfor var in variables:\n\t\t\tdiffadd(var, num, lbfd)\n\t\n\t\t#change time to future\n\t\tendtimestring = lbfd.time.units[-15:]\n\t\told_yyyy_timestamp = int(lbfd.time.units[-19:-15])\n\t\tnew_yyyy_timestamp = old_yyyy_timestamp + changeyears\n\t\tlbfd.time.attrs['units'] = f'seconds since {new_yyyy_timestamp}{endtimestring}'\n\n\t\tlbfd = computeQVnew(lbfd, num, RH_old, RH_S_old)\n\t\t\n\t\tendpart = lbfdnum[-9:]\n\t\tlbfdyear = int(lbfdnum[4:8])\n\t\tlbfdyear = lbfdyear + changeyears\n\t\tlbfd.to_netcdf(f'{outputpath}/lbfd{lbfdyear}{endpart}', mode='w')\n\t\tlbfd.close()\n\npref, pref_sfc = getpref(vcflat, terrainpath, height_flat)\nlbfdadapt(lbfdpath, outputpath, Diffspath, difftimesteps, changeyears, pref, pref_sfc)\n","sub_path":"Postprocess_CCLM/lbfd_adapt.py","file_name":"lbfd_adapt.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"474769699","text":"from scipy.stats import sem, t\nfrom math import sqrt\nfrom numpy import average, std\n\nimport numpy as np\nfrom scipy import stats\n\n\ndef get_confidence_interval_for_mean(array, length, math_expectation):\n confidence_level = 0.95\n degrees_of_freedom = length - 1\n\n # sem - standard error of the mean\n # SE = sigma / sqrt(n) , where sigma is \"standart deviation\"\n\n intervals_bounds = t.interval(confidence_level, degrees_of_freedom,\n math_expectation, sem(array))\n\n return intervals_bounds[0], intervals_bounds[1]\n\n\ndef get_confidence_interval_for_mean_from_column(column, math_expectation):\n return get_confidence_interval_for_mean(column.values, column.values.size, math_expectation)\n\n\ndef get_confidence_interval_for_variance(array, length):\n confidence_level = 0.95\n degrees_of_freedom = length - 1\n\n alpha = 1 - confidence_level # significance level\n variance = np.var(array, ddof=1)\n\n print('variance')\n print(variance)\n\n upper_chi2 = stats.chi2.ppf(alpha / 2, degrees_of_freedom)\n lower_chi2 = stats.chi2.ppf(1 - alpha / 2, degrees_of_freedom)\n\n upper = degrees_of_freedom * variance / upper_chi2\n lower = degrees_of_freedom * variance / lower_chi2\n\n return lower, upper\n\n\ndef get_confidence_interval_for_variance_from_column(column):\n return get_confidence_interval_for_variance(column.values, column.values.size)\n","sub_path":"StatisticalHypotheses/confidence_intervals.py","file_name":"confidence_intervals.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"479975848","text":"# importing sqlite 3 module\n\nimport sqlite3\n# connecting to the database\nconnection = sqlite3.connect(\"demo_data.db\")\n\n#cursor\ncursor = connection.cursor()\n\n# CREATE A TABLE\n\nsql = \"\"\"\nCREATE TABLE IF NOT EXISTS demo (s TEXT, x INTEGER, y INTEGER);\n\"\"\"\ncursor.execute(sql)\n\n#\n# INSERT DATA INTO THE PASSENGERS TABLE\n#\n\ninsertion_query = \"\"\"INSERT INTO demo VALUES (\"'g'\", 3, 9), (\"'v'\", 5, 7), (\"'f'\", 8,7);\"\"\"\ncursor.execute(insertion_query)\n\n# COMMIT\nconnection.commit() # actually save the records / run the transaction to insert rows\n\n# QUERY\n\n\nquery1 = \"\"\"\nSELECT * from demo;\n\"\"\"\n\ncursor = connection.cursor()\nresult1 = cursor.execute(query1).fetchall()\nprint(\"Table contents\", result1[0:][0:])\nconnection.commit()\n\n############################################\n\nquery2 = \"\"\"\nSELECT COUNT( * ) as \"Number of Rows\" from demo;\n\"\"\"\ncursor = connection.cursor()\nresult2 = cursor.execute(query2).fetchall()\nprint(\"Number of rows\", result2[0])\nconnection.commit()\n\n\n###################\nquery3 = \"\"\"\nSELECT COUNT( * ) as \"Number of Rows where both x and y are at least 5\" from demo WHERE x>4 AND y>4;\n\"\"\"\n\ncursor = connection.cursor()\nresult3 = cursor.execute(query3).fetchall()\nprint(\"Number of rows where both x and y are at least 5\", result3[0])\nconnection.commit()\n\n\n######################################\nquery4 = \"\"\"\nSELECT COUNT (DISTINCT y) as \"Unique values of y\" from demo;\n\"\"\"\ncursor = connection.cursor()\nresult4 = cursor.execute(query4).fetchall()\nprint(\"Unique Values in 'y'\", result4[0])\nconnection.commit()\n\n\n\n\n# close\ncursor.close()\nconnection.close()","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"504972823","text":"import copy\nfrom . import file_manager\nfrom .templates import svg_group\nfrom .elements import Element, SVG, Coords, BoundingBox, BoundingCoords\nfrom . import elements as elem\n\n\nclass Component(SVG):\n \"\"\"Container object that manages child Components and/or Elements as a group.\n\n :param children: Components and/or elements, defaults to None\n :type children: SVG subtypes, optional\n \"\"\"\n\n config = {}\n\n def __init__(self, children=None, *args, **kwargs):\n \"\"\"[summary]\"\"\"\n self.children = []\n super().__init__(*args, **kwargs)\n\n @property\n def bounding_coords(self):\n \"\"\"Coordinates of the components's bounding rectangle.\n\n :return: (x_min, y_min, x_max, y_max)\n :rtype: BoundingCoords (namedtuple)\n \"\"\"\n # Untransformed bounding coords\n x_min = y_min = x_max = y_max = 0\n for child in self.children:\n try:\n child_coords = child.bounding_coords\n x_min = min(x_min, child_coords.x_min)\n y_min = min(y_min, child_coords.y_min)\n x_max = max(x_max, child_coords.x_max)\n y_max = max(y_max, child_coords.y_max)\n except AttributeError:\n # The child has no bounding_coords.\n pass\n\n x_min, x_max = sorted(\n [(self.x + x_min) * self.scale.x, (self.x + x_max) * self.scale.x]\n )\n y_min, y_max = sorted(\n [(self.y + y_min) * self.scale.y, (self.y + y_max) * self.scale.y]\n )\n\n return BoundingCoords(x_min, y_min, x_max, y_max)\n\n @property\n def bounding_rect(self):\n \"\"\"Components's coordinates and size.\n\n :return: (x, y, width, height)\n :rtype: BoundingBox (namedtuple)\n \"\"\"\n x_min, y_min, x_max, y_max = self.bounding_coords\n return BoundingBox(x_min, y_min, x_max - x_min, y_max - y_min)\n\n @property\n def width(self):\n \"\"\"Calculated width that encompasses all child elements\n\n :return: value representing width in pixels\n :rtype: int\n \"\"\"\n try:\n x_min, y_min, x_max, y_max = self.bounding_coords\n return x_max - x_min\n except ValueError:\n # Component has no children with bounding_coords\n return 0\n\n @property\n def height(self):\n \"\"\"Calculated height that encompasses all child elements\n\n :return: value representing height in pixels\n :rtype: int\n \"\"\"\n try:\n x_min, y_min, x_max, y_max = self.bounding_coords\n return y_max - y_min\n except ValueError:\n # Component has no children with bounding_coords\n return 0\n\n @property\n def scale(self):\n \"\"\"See :func:`~pinout.elements.SVG.scale`\"\"\"\n return self._scale\n\n @scale.setter\n def scale(self, value):\n self._scale = value\n for child in self.children:\n if issubclass(type(child), Element):\n child.scale = self.scale\n\n def add(self, instance):\n \"\"\"Add an instance to the component's children.\n\n :param instance: Component or Element\n :type instance: Component or Element\n :return: instance attribute\n :rtype: Component or Element\n \"\"\"\n self.children.append(instance)\n return instance\n\n @staticmethod\n def patch_config(source, patch):\n \"\"\"Recursively update source with patch dict items.\"\"\"\n try:\n for key, val in patch.items():\n if type(val) == dict:\n source.setdefault(key, {})\n Component.patch_config(source[key], patch[key])\n else:\n source[key] = val\n except KeyError:\n # patch has no items\n pass\n return source\n\n def render(self):\n \"\"\"Render Component, and children, as SVG markup.\n\n :return: SVG markup of component including all children.\n :rtype: str\n \"\"\"\n output = \"\"\n for child in self.children:\n output += child.render()\n return svg_group.render(\n x=self.x,\n y=self.y,\n tag=self.tag,\n content=output,\n scale=self.scale,\n )\n\n\nclass PinLabelSet(Component):\n \"\"\"Add rows of PinLabels to a 'header' of pins\n\n :param offset: Offset of the first PinLabelRow from the origin\n :type offset: (x, y) tuple\n :param labels: List of PinLabelRows\n :type labels: List\n :param pitch: Offset between each PinLabelRow, defaults to (1, 1)\n :type pitch: (x, y) tuple, optional\n \"\"\"\n\n def __init__(self, offset, labels, pitch=(1, 1), *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Extract scale and update x and y of pinlabelset instance\n offset, self.scale = self.extract_scale(offset)\n self.x = self.x * self.scale.x\n self.y = self.y * self.scale.y\n\n pitch = Coords(*pitch)\n\n # Create a Component for each row in 'labels'\n for i, label_list in enumerate(labels):\n pin_x = pitch.x * i * self.scale.x\n pin_y = pitch.y * i * self.scale.y\n row_offset = offset\n if pitch[1] == 0:\n # Horizontal pinset require label_rows to offset vertically\n row_offset = Coords(offset.x - pin_x, offset.y + abs(pin_x))\n\n row = self.add(\n Component(\n x=pin_x + row_offset.x,\n y=pin_y + row_offset.y,\n )\n )\n\n # Create a leaderline\n leaderline_config = copy.deepcopy(self.config[\"leaderline\"])\n vertical_move = f\"V {row_offset.y}\" if row_offset.y != 0 else \"\"\n\n horizontal_move = (\n f\"H {pin_x + row_offset.x + (pitch.x * i * -1 * self.scale.x)}\"\n if row_offset.x != 0\n else \"\"\n )\n\n definition = f\"M 0 0 {vertical_move} {horizontal_move}\"\n leaderline_config[\"bullet_radius\"] = self.config[\"bullet_radius\"]\n\n leaderline = self.add(\n elem.Path(\n x=pin_x,\n y=pin_y,\n definition=definition,\n config=leaderline_config,\n )\n )\n\n # Add labels to row\n for j, label in enumerate(label_list):\n label = dict(zip((\"text_content\", \"tag\", \"config\"), label))\n\n # Copy config and patch with supplied config\n label_config = copy.deepcopy(self.config)\n self.patch_config(label_config, label.get(\"config\", {}))\n # Patch config with tag styles\n tag_bg_color = Component.config[\"tags\"][label[\"tag\"]][\"bg_color\"]\n tag_fg_color = Component.config[\"tags\"][label[\"tag\"]][\"fg_color\"]\n self.patch_config(\n label_config,\n {\n \"label\": {\"rect\": {\"fill\": tag_bg_color}, \"text\":{\"fill\": tag_fg_color}},\n \"leaderline\": {\"stroke\": tag_bg_color},\n },\n )\n\n # Match leaderline to first label tag color\n if j == 0 and not leaderline.config[\"force_color\"]:\n leaderline.config[\"stroke\"] = tag_color\n\n # add label's leaderline\n if self.config[\"leaderlines_between\"]:\n label_offset = Coords(*label_config[\"offset\"])\n self.patch_config(\n label_config,\n {\"leaderline\": {\"stroke\": tag_color}},\n )\n definition = f\"M {row.width} 0 h {label_offset.x}\"\n row.add(\n elem.Path(\n x=row.width,\n y=0,\n width=label_offset.x,\n height=self.config[\"leaderline\"][\"stroke_width\"],\n scale=self.scale,\n definition=definition,\n config=label_config[\"leaderline\"],\n )\n )\n\n row.add(\n elem.Label(\n text_content=label[\"text_content\"],\n x=row.width,\n y=-label_config[\"label\"][\"rect\"][\"height\"] / 2,\n width=label_config[\"label\"][\"rect\"][\"width\"],\n height=label_config[\"label\"][\"rect\"][\"height\"],\n scale=self.scale,\n config=label_config[\"label\"],\n )\n )\n\n\nclass Legend(Component):\n \"\"\"Provide a colour coded legend to describe pin labels.\n\n :param categories: List of tags to include in legend\n :type categories: [, , ...] List\n \"\"\"\n\n def __init__(self, categories, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # NOTE: pad.y sets the text **baseline**\n pad = Coords(*self.config[\"padding\"])\n row_height = self.config[\"row_height\"]\n swatch_width = row_height * 2 / 1.2\n swatch_height = row_height * 2 / 3\n categories = categories or Component.config[\"tags\"].keys()\n for i, tag in enumerate(categories):\n entry = self.add(\n Component(x=pad.x, y=pad.y + row_height * i, tag=self.config[\"tag\"])\n )\n entry.add(\n elem.Text(\n Component.config[\"tags\"][tag][\"title\"],\n x=swatch_width + 10,\n y=-4,\n width=self.config[\"rect\"][\"width\"],\n height=row_height,\n config=self.config[\"text\"],\n )\n )\n\n # Create icon based on pinlabel config\n pinlabel_config = copy.deepcopy(Component.config[\"pinlabel\"])\n tag_color = Component.config[\"tags\"][tag][\"bg_color\"]\n pinlabel_patch = {\n \"offset\": (-swatch_width / 2, 0),\n \"label\": {\n \"rect\": {\n \"fill\": tag_color,\n \"height\": swatch_height,\n \"width\": swatch_width,\n \"rx\": pinlabel_config[\"label\"][\"rect\"][\"rx\"],\n },\n },\n \"leaderline\": {\n \"stroke\": tag_color,\n },\n }\n self.patch_config(pinlabel_config, pinlabel_patch)\n \n entry.add(\n elem.Label(\n text_content=\"\",\n x=0,\n y=-pinlabel_config[\"label\"][\"rect\"][\"height\"] / 2\n - self.config[\"text\"][\"size\"] / 2,\n width=swatch_width,\n height=swatch_height,\n config=pinlabel_config[\"label\"],\n ))\n\n #definition = f\"M {swatch_size} {-pinlabel_config['label']['text']['size'] / 2} h {swatch_size/2}\"\n #entry.add(\n # elem.Path(\n # definition=definition,\n # x=swatch_size,\n # y=-pinlabel_config[\"label\"][\"text\"][\"size\"] / 2,\n # width=swatch_size / 2,\n # height=pinlabel_config[\"leaderline\"][\"stroke_width\"],\n # config=pinlabel_config[\"leaderline\"],\n # )\n #)\n\n # Add an panel *behind* component\n self.config[\"rect\"][\"height\"] = (\n row_height * len(categories) + pad.y - self.config[\"text\"][\"size\"]\n )\n self.children.insert(\n 0,\n elem.Rect(\n x=0,\n y=0,\n width=self.config[\"rect\"][\"width\"],\n height=self.config[\"rect\"][\"height\"],\n scale=self.scale,\n config=self.config[\"rect\"],\n ),\n )\n\n\nclass Annotation(Component):\n \"\"\"Add text with a leaderline styled as an annotation.\n\n :param text_content: Annotation text\n :type text_content: String or List\n \"\"\"\n\n def __init__(self, text_content, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Extract scale from offset and update x and y\n offset, self.scale = self.extract_scale(self.config[\"offset\"])\n\n # override scale if explicitly provided\n if \"scale\" in kwargs.keys():\n self.scale = Coords(*kwargs[\"scale\"])\n\n self.x = self.x * self.scale.x\n self.y = self.y * self.scale.y\n\n label_padding = Coords(*self.config[\"label\"][\"padding\"])\n\n # Attempt to split on '\\n' and convert to list\n if type(text_content) == str:\n text_content = text_content.split(\"\\n\")\n\n # Calculate label dimensions\n line_height = self.config[\"label\"][\"text\"][\"line_height\"]\n font_height = self.config[\"label\"][\"text\"][\"size\"]\n top_padding = label_padding.y - (line_height - font_height)\n label_height = (\n len(text_content) * self.config[\"label\"][\"text\"][\"line_height\"]\n + label_padding.y\n + top_padding\n )\n self.config[\"label\"][\"rect\"][\"height\"] = label_height\n\n # label required nudging to align with leaderline\n stroke_shim = self.config[\"leaderline\"][\"stroke_width\"] / 2\n\n # Annotation label\n # shift label if flipped\n label_translate_y = label_height if self.scale.y == 1 else 0\n label = self.add(\n Component(\n tag=\"anno_label\",\n x=offset.x - stroke_shim,\n y=offset.y - label_translate_y + stroke_shim,\n )\n )\n # Add background rect to label\n label.add(\n elem.Rect(\n y=0,\n width=self.config[\"label\"][\"rect\"][\"width\"],\n height=self.config[\"label\"][\"rect\"][\"height\"],\n config=self.config[\"label\"][\"rect\"],\n )\n )\n # Add textblock to label\n label.add(\n elem.TextBlock(\n text_content,\n x=label_padding.x,\n y=top_padding,\n width=self.config[\"label\"][\"rect\"][\"width\"] - label_padding.x * 2,\n height=self.config[\"label\"][\"rect\"][\"height\"] - label_padding.y,\n config=self.config[\"label\"],\n scale=self.scale,\n )\n )\n\n # Leaderline\n # leaderline rect\n leaderline_rect = self.add(\n elem.Rect(\n x=-self.config[\"leaderline\"][\"rect\"][\"width\"] / 2,\n y=-self.config[\"leaderline\"][\"rect\"][\"height\"] / 2,\n width=self.config[\"leaderline\"][\"rect\"][\"width\"],\n height=self.config[\"leaderline\"][\"rect\"][\"height\"],\n config=self.config[\"leaderline\"][\"rect\"],\n )\n )\n\n # leaderline start location at edge of leaderline_rect\n start_y = 0\n start_x = 0\n if offset.y > leaderline_rect.height / 2:\n start_y = leaderline_rect.height / 2\n elif -leaderline_rect.height / 2 < offset.y < leaderline_rect.height / 2:\n start_x = leaderline_rect.width / 2\n\n # leaderline path\n vertical_move = f\"V {offset.y}\" if offset.y != 0 else \"\"\n horizontal_move = f\"H {offset.x + label.width - stroke_shim}\"\n label_width = self.config[\"label\"][\"rect\"][\"width\"]\n horizontal_move = f\"H {offset.x + label.width - stroke_shim}\"\n\n path_definition = f\"M {start_x} {start_y} {vertical_move} {horizontal_move}\"\n\n self.add(elem.Path(path_definition, config=self.config[\"leaderline\"]))\n","sub_path":"pinout/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":15841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"254108879","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom ..protocols import sru\nfrom ..schemas import xml\n\nBASE = \"http://z3950.kobv.de/k2\"\nVERSION = \"1.1\"\nSCHEMA = \"dc\" # \"marcxml\"\n\n\ndef explain(store=False, path=\"\"):\n result = sru.explain(BASE, VERSION)\n if not store:\n xml.pretty(result)\n else:\n file = xml.filepath(\"sru\", \"kobv\", \"\", \"\")\n xml.writer(result, file, path=path)\n","sub_path":"librair/catalogs/kobv.py","file_name":"kobv.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"629743537","text":"#!/usr/bin/python\n#\n# DiffMerge Launch and Compare script\n# Copyright (c) Zennaware GmbH, 2012. All rights reserved.\n#\n\nfrom AppKit import NSWorkspace\nimport sys\nimport os\n\nbundleIdentifier = 'com.sourcegear.DiffMerge'\nhelperPath = 'Contents/MacOS/DiffMerge'\n\nappPath = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_(bundleIdentifier)\n\nif appPath is None:\n\terror = 'Application with the bundle identifier \"%s\" does not exist' % (bundleIdentifier)\n\traise ValueError(error)\n\nos.system('\"%s\" -nosplash -result=\"%s\" -t1=\"%s\" -t2=\"%s\" -t3=\"%s\" -merge \"%s\" \"%s\" \"%s\"' % (os.path.join(appPath, helperPath), sys.argv[7], sys.argv[2], sys.argv[6], sys.argv[4], sys.argv[1], sys.argv[3], sys.argv[5]))","sub_path":"MacSoft/Cornerstone.app/Contents/Library/CompareTools/DiffMerge.compareToolSupport/Contents/Resources/Scripts/LaunchAndMerge.py","file_name":"LaunchAndMerge.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"67259802","text":"#!/usr/bin/env python3\n\nimport gzip\nimport io\nimport argparse\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='fasta statistics')\n parser.add_argument('fasta',\n help='fasta file')\n parser.add_argument('-l', metavar='len', type=int, default=0,\n help='minimun sequence length (0)')\n parser.add_argument('-s', action='store_true',\n help='print single line format')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = parse_args()\n FIN = args.fasta\n FIN = io.BufferedReader(gzip.open(FIN)) if FIN.endswith('.gz') else open(FIN, 'rb')\n cutoff = args.l\n\n lengths = {}\n Ns = {}\n for line in FIN:\n line = line.strip()\n if line.startswith(b'>'):\n title = line[1:].decode()\n lengths[title] = 0\n Ns[title] = 0\n else:\n lengths[title] += len(line)\n Ns[title] += (line.count(b'N') + line.count(b'n'))\n FIN.close()\n\n lengths = sorted(filter(lambda x: x[1] > cutoff, lengths.items()), key=lambda x: x[1], reverse=True)\n total_len = sum([x[1] for x in lengths])\n titles_pass = [x[0] for x in lengths]\n total_N = sum([x[1] for x in filter(lambda x: x[0] in titles_pass, Ns.items())])\n total_seqs = len(lengths)\n\n auN = sum([x[1]**2 for x in lengths]) / total_len\n total_len_50 = total_len * 0.5\n total_len_90 = total_len * 0.9\n ctg_N50 = None\n ctg_N90 = None\n accu_len = 0\n above_len = [1e2, 1e3, 1e4, 1e5, 1e6]\n above_counts = [0] * len(above_len)\n\n for n, (k, v) in enumerate(lengths, 1):\n accu_len += v\n if not ctg_N50 and accu_len > total_len_50:\n ctg_N50 = (n, k, v)\n if not ctg_N90 and accu_len > total_len_90:\n ctg_N90 = (n, k, v)\n for i in range(len(above_len)):\n if v > above_len[i]:\n above_counts[i] += 1\n\n if args.s:\n # total_base seq_num mean(kb) max(kb) N50(kb) L50 N90(kb) L90 N\n print(\n total_len,\n total_seqs,\n '{:.1f}'.format(total_len / total_seqs / 1e3),\n '{:.1f}'.format(lengths[0][1] / 1e3),\n '{:.1f}'.format(ctg_N50[2] / 1e3),\n ctg_N50[0],\n '{:.1f}'.format(ctg_N90[2] / 1e3),\n ctg_N90[0],\n total_N,\n sep='\\t'\n )\n elif total_seqs < 3:\n print('''\\\ninput fasta file: {}\nlength cutoff: {}\n\nminimum length: {} ({})\nmaximum length: {} ({})\ntotal seqs: {}\ntotal length: {}\navg. length: {:.3f}\nnumber of Ns: {} ({:.3%})\n'''.format(args.fasta,\n cutoff,\n lengths[-1][1], lengths[-1][0],\n lengths[0][1], lengths[0][0],\n total_seqs,\n total_len,\n total_len / total_seqs,\n total_N, total_N / total_len,\n ))\n else:\n print('''\\\ninput fasta file: {}\nlength cutoff: {}\n\nminimum length: {} ({})\nmaximum length: {} ({})\n2nd long seq: {} ({})\n3rd long seq: {} ({})\ntotal seqs: {}\ntotal length: {}\navg. length: {:.3f}\nnumber of Ns: {} ({:.3%})\nL50: {} ({})\nN50: {}\nL90: {} ({})\nN90: {}\nauN: {:.3f}\n'''.format(args.fasta,\n cutoff,\n lengths[-1][1], lengths[-1][0],\n lengths[0][1], lengths[0][0],\n lengths[1][1], lengths[1][0],\n lengths[2][1], lengths[2][0],\n total_seqs,\n total_len,\n total_len / total_seqs,\n total_N, total_N / total_len,\n ctg_N50[0], ctg_N50[1],\n ctg_N50[2],\n ctg_N90[0], ctg_N90[1],\n ctg_N90[2],\n auN\n ))\n\n print('''\\\nseq counts:\n> 100 bp: {}\n> 1 Kbp: {}\n> 10 Kbp: {}\n> 100 Kbp: {}\n> 1 Mbp: {}\n'''.format(above_counts[0],\n above_counts[1],\n above_counts[2],\n above_counts[3],\n above_counts[4]\n ))\n\n print('# total_base seq_num mean(kb) max(kb) N50(kb) L50 N90(kb) L90 N')\n print(\n total_len,\n total_seqs,\n '{:.1f}'.format(total_len / total_seqs / 1e3),\n '{:.1f}'.format(lengths[0][1] / 1e3),\n '{:.1f}'.format(ctg_N50[2] / 1e3),\n ctg_N50[0],\n '{:.1f}'.format(ctg_N90[2] / 1e3),\n ctg_N90[0],\n total_N,\n sep='\\t'\n )\n","sub_path":"fasta_stats.py","file_name":"fasta_stats.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"58756677","text":"# Input: S = \"loveleetcode\", C = 'e'\n# 0 1 2 3 4 5 6 7 8 9 10 11\n# l o v e l e e t c o d e\n# Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]\n\n\ndef shortest_to_char(string: str, char: str):\n result = []\n for i in range(len(string)):\n right = find_closest_right(string, char, i)\n left = find_closest_left(string, char, i)\n if right < left:\n result.append(right)\n else:\n result.append(left)\n return result\n\n\ndef find_closest_right(string, char, index):\n for i in range(index, len(string), 1):\n if string[i] == char:\n return i - index\n return len(string)\n\n\ndef find_closest_left(string, char, index):\n for i in range(index, -1, -1):\n if string[i] == char:\n return index - i\n return len(string)\n\n\nassert shortest_to_char('baaa', 'b') == [0, 1, 2, 3]\n","sub_path":"leetcode/821.py","file_name":"821.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"521243688","text":"import logging\nimport pytest\nimport time\nfrom tests.common.helpers.assertions import pytest_require, pytest_assert\nfrom tests.common.dualtor.mux_simulator_control import toggle_all_simulator_ports_to_lower_tor # lgtm[py/unused-import]\nfrom tests.common.dualtor.dual_tor_utils import upper_tor_host, lower_tor_host, dualtor_info, get_t1_active_ptf_ports, is_tunnel_qos_remap_enabled\nfrom tests.common.fixtures.ptfhost_utils import change_mac_addresses, run_icmp_responder, run_garp_service # lgtm[py/unused-import]\nimport ptf.packet as scapy\nfrom ptf.mask import Mask\nfrom ptf import testutils\nfrom ptf.testutils import simple_tcp_packet, simple_ipv4ip_packet\n\npytestmark = [\n pytest.mark.topology('t0')\n]\n\nlogger = logging.getLogger(__name__)\n\nSERVER_IP = \"192.168.0.2\"\nDUMMY_IP = \"1.1.1.1\"\nDUMMY_MAC = \"aa:aa:aa:aa:aa:aa\"\n\n@pytest.fixture(scope='module', autouse=True)\ndef check_running_condition(tbinfo, duthost):\n \"\"\"\n The test can only be running on tunnel_qos_remap enabled dualtor testbed\n \"\"\"\n # Check dualtor topo\n pytest_require(\"dualtor\" in tbinfo[\"topo\"][\"name\"], \"Only run on dualtor testbed.\", True)\n \n # Check tunnel_qos_remap is enabled\n pytest_require(is_tunnel_qos_remap_enabled(duthost), \"Only run when tunnel_qos_remap is enabled\", True)\n\n\ndef _build_testing_packet(src_ip, dst_ip, active_tor_mac, standby_tor_mac, active_tor_ip, standby_tor_ip, inner_dscp, outer_dscp, ecn=1):\n pkt = simple_tcp_packet(\n eth_dst=standby_tor_mac,\n ip_src=src_ip,\n ip_dst=dst_ip,\n ip_dscp=inner_dscp,\n ip_ecn=ecn,\n ip_ttl=64\n )\n # The ttl of inner_frame is decreased by 1\n pkt.ttl -= 1\n ipinip_packet = simple_ipv4ip_packet(\n eth_dst=active_tor_mac,\n eth_src=standby_tor_mac,\n ip_src=standby_tor_ip,\n ip_dst=active_tor_ip,\n ip_dscp=outer_dscp,\n ip_ecn=ecn,\n inner_frame=pkt[IP]\n )\n pkt.ttl += 1\n exp_tunnel_pkt = Mask(ipinip_packet)\n exp_tunnel_pkt.set_do_not_care_scapy(scapy.Ether, \"dst\")\n exp_tunnel_pkt.set_do_not_care_scapy(scapy.Ether, \"src\")\n exp_tunnel_pkt.set_do_not_care_scapy(scapy.IP, \"id\") # since src and dst changed, ID would change too\n exp_tunnel_pkt.set_do_not_care_scapy(scapy.IP, \"ttl\") # ttl in outer packet is set to 255\n exp_tunnel_pkt.set_do_not_care_scapy(scapy.IP, \"chksum\") # checksum would differ as the IP header is not the same\n\n return pkt, exp_tunnel_pkt\n\n\ndef test_encap_dscp_rewrite(ptfhost, upper_tor_host, lower_tor_host, toggle_all_simulator_ports_to_lower_tor, tbinfo, ptfadapter):\n \"\"\"\n The test is to verify the dscp rewriting of encapped packets.\n Test steps\n 1. Toggle mux to lower tor, so all mux ports are standby on upper_tor\n 2. Generate packets with certain DSCP value\n 3. Send the generated packets via portchannels\n 4. Verify the packets are encapped with expected DSCP value \n \"\"\"\n DSCP_COMBINATIONS = [\n # DSCP in generated packets, expected DSCP in encapped packets\n (8, 8),\n (0, 0),\n (33, 33),\n (3, 2),\n (4, 6),\n (46, 46),\n (48, 48)\n ]\n dualtor_meta = dualtor_info(ptfhost, upper_tor_host, lower_tor_host, tbinfo)\n active_tor_mac = lower_tor_host.facts['router_mac']\n \n t1_ports = get_t1_active_ptf_ports(upper_tor_host, tbinfo)\n # Always select the first port in first LAG as src_port\n src_port = list(t1_ports.values())[0][0]\n dst_ports = []\n for ports in t1_ports.values():\n dst_ports.extend(ports)\n\n for dscp_combination in DSCP_COMBINATIONS:\n pkt, expected_pkt = _build_testing_packet(src_ip=DUMMY_IP,\n dst_ip=SERVER_IP,\n active_tor_mac=active_tor_mac,\n standby_tor_mac=dualtor_meta['standby_tor_mac'],\n active_tor_ip=dualtor_meta['active_tor_ip'],\n standby_tor_ip=dualtor_meta['standby_tor_ip'],\n inner_dscp=dscp_combination[0],\n outer_dscp=dscp_combination[1],\n ecn=1)\n ptfadapter.dataplane.flush()\n # Send original packet\n testutils.send(ptfadapter, src_port, pkt)\n # Verify encaped packet\n testutils.verify_packet_any_port(ptfadapter, expected_pkt, dst_ports)\n\ndef _check_queue_counter(duthost, intfs, queue, counter):\n output = duthost.shell('show queue counters')['stdout_lines']\n\n for intf in intfs:\n for line in output:\n fields = line.split()\n if len(fields) == 6 and fields[0] == intf and fields[1] == 'UC{}'.format(queue):\n if int(fields[2]) >= counter:\n return True\n \n return False\n\ndef test_bounced_back_traffic_in_expected_queue(ptfhost, upper_tor_host, lower_tor_host, toggle_all_simulator_ports_to_lower_tor, tbinfo, ptfadapter):\n \"\"\"\n The test case is to verify the encapped packet is mapped to the correct queue\n Test steps:\n 1. Toggle mux to lower tor, so all mux ports are standby on upper_tor\n 2. Generate packets with certain DSCP value\n 3. Send the generated packets via portchannels\n 4. Verify the packets are outgoing from expected queue \n \"\"\"\n TEST_DATA = [\n #DSCP QUEUE\n (8, 0),\n (0, 1),\n (33, 1),\n (3, 2),\n (4, 6),\n (46, 5),\n (48, 7)\n ]\n dualtor_meta = dualtor_info(ptfhost, upper_tor_host, lower_tor_host, tbinfo)\n active_tor_mac = lower_tor_host.facts['router_mac']\n t1_ports = get_t1_active_ptf_ports(upper_tor_host, tbinfo)\n # Always select the first port in first LAG as src_port\n src_port = list(t1_ports.values())[0][0]\n mg_facts = upper_tor_host.get_extended_minigraph_facts(tbinfo)\n portchannel_info = mg_facts['minigraph_portchannels']\n tor_pc_intfs = list()\n for pc in portchannel_info.values():\n for member in pc['members']:\n tor_pc_intfs.append(member)\n PKT_NUM = 100\n\n for dscp, queue in TEST_DATA:\n pkt, _ = _build_testing_packet(src_ip=DUMMY_IP,\n dst_ip=SERVER_IP,\n active_tor_mac=active_tor_mac,\n standby_tor_mac=dualtor_meta['standby_tor_mac'],\n active_tor_ip=dualtor_meta['active_tor_ip'],\n standby_tor_ip=dualtor_meta['standby_tor_ip'],\n inner_dscp=dscp,\n outer_dscp=0,\n ecn=1)\n # Clear queuecounters before sending traffic\n upper_tor_host.shell('sonic-clear queuecounters')\n # Send original packet\n testutils.send_packet(ptfadapter, src_port, pkt, PKT_NUM)\n # Verify queue counters in all possible interfaces\n time.sleep(15)\n\n pytest_assert(_check_queue_counter(upper_tor_host, tor_pc_intfs, queue, PKT_NUM),\n \"The queue counter for DSCP {} Queue {} is not as expected\".format(dscp, queue))\n\n","sub_path":"tests/qos/test_tunnel_qos_remap.py","file_name":"test_tunnel_qos_remap.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"44867506","text":"\nimport argparse\nimport os\nimport logging\nimport shutil\nfrom pprint import pprint\nimport sys\n\nimport pyinotify\nimport jinja2\n\nif __name__ == '__main__' and __package__ is None:\n parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n sys.path.insert(0, parent_dir)\n import src\n __package__ = 'src'\n\n__version__ = '0.1.0'\n\nlogger = logging.getLogger()\n\ndef clean(build_dir):\n if os.path.isdir(build_dir):\n contents = [os.path.join(build_dir, i) for i in os.listdir(build_dir)]\n [shutil.rmtree(i) if os.path.isdir(i) else os.unlink(i) for i in contents]\n\ndef setup_logging(screen_level):\n \n logger_level = min([ screen_level, ])\n logger.setLevel(logger_level)\n \n # Create screen handler\n handler = logging.StreamHandler()\n handler.setLevel(screen_level)\n formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \ndef start_watching():\n raise NotImplementedError()\n\ndef configure_command_line_args():\n parser = argparse.ArgumentParser(\n description='Build static web assets from source templates'\n )\n \n parser.add_argument(\n '--version',\n action='store_const',\n const=1,\n help='Print the version number and exit'\n )\n \n parser.add_argument(\n '--watch',\n action='store_const',\n const=1,\n help='Start process to monitor source directory'\n )\n \n parser.add_argument(\n '--clean',\n action='store_const',\n const=1,\n help='Empty the build directory before proceeding, if it exists'\n )\n \n parser.add_argument(\n '-c',\n '--config-file-path',\n help='Path to the config file'\n )\n \n parser.add_argument(\n 'source_dir',\n nargs='?'\n )\n \n parser.add_argument(\n 'build_dir',\n nargs='?'\n )\n \n return parser\n\ndef normalize_path(raw):\n if raw.startswith('/'):\n return raw\n return os.path.join(os.getcwd(), raw)\n\ndef build(**kwargs):\n source_dir = kwargs['source_dir']\n build_dir = kwargs['build_dir']\n templating_environment = kwargs['templating_environment']\n \n for i in os.walk(source_dir):\n # Get the root directory\n relative_dir = i[0].replace(source_dir, '')\n if relative_dir.startswith('/'):\n relative_dir = relative_dir.lstrip('/')\n root_dir = os.path.join(build_dir, relative_dir)\n \n # Make the root directory\n if not os.path.isdir(root_dir):\n os.makedirs(root_dir)\n \n for filename in [j for j in i[2] if not j.startswith('__')]:\n template_path = '/'.join([ relative_dir, filename ])\n target_path = '/'.join([ root_dir, filename ])\n template = templating_environment.get_template(template_path)\n output = template.render()\n with open(target_path, mode='w') as fp:\n fp.write(output)\n\ndef main():\n args = configure_command_line_args().parse_args()\n #print(args)\n \n if args.version == 1:\n print('Version:', __version__)\n return\n \n if not args.config_file_path:\n raise Exception('Configuration file path not specified')\n \n if not args.source_dir:\n raise Exception('Source directory not specified')\n \n if not args.build_dir:\n raise Exception('Build directory not specified')\n \n # Get the source and build directories\n config_file_path = normalize_path(args.config_file_path)\n #print('config file path:', config_file_path)\n \n source_dir = normalize_path(args.source_dir)\n #print('source directory:', source_dir)\n \n build_dir = normalize_path(args.build_dir)\n #print('build directory:', build_dir)\n \n # Load the configuration file\n if not os.path.isfile(config_file_path):\n raise Exception('Config file ({}) not found'.format(config_file_path))\n \n config_file_parent_dir = os.path.dirname(config_file_path)\n if not config_file_parent_dir in sys.path:\n sys.path.insert(0, config_file_parent_dir)\n import config\n \n # Configure logging\n setup_logging(config.log_level_screen)\n logger.debug('Command line args: %s', args)\n \n logger.info('config_file_path: %s', config_file_path)\n logger.info('build_dir: %s', build_dir)\n logger.info('source_dir: %s', source_dir)\n \n if args.clean == 1:\n clean(build_dir)\n \n # Generate Jinja2 environment\n templating_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(source_dir))\n \n build_kwargs = {\n 'source_dir': source_dir,\n 'build_dir': build_dir,\n 'templating_environment': templating_environment\n }\n \n build(**build_kwargs)\n \n if args.watch == 1:\n start_watching()\n \nif __name__ == '__main__':\n main()\n ","sub_path":"src/build_ui.py","file_name":"build_ui.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"64026735","text":"#variable\n#data types /int, float, str/\n# input(), print(), type()\n#function, method, arga\na=12\nb=5\nc=a**b\nprint(c)\nprint(a+b)\na = int(input(\"a too: \"))\nb = int(input(\"b too: \"))\nprint(a+b)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290168041","text":"\n#!/bin/python\n\nfrom __future__ import print_function\nimport json,sys\n\ntry:\n minAgeFromEpoc = sys.argv[1]\n writeIndex = sys.argv[2]\n output = sys.argv[3]\nexcept IndexError:\n raise SystemExit(f\"Usage: {sys.argv[0]} \")\n\ntry:\n response = json.loads(output)\nexcept ValueError:\n raise SystemExit(f\"Invalid JSON: {output}\")\n\nlastIndex = len(response) - 1\n\nif 'error' in response[lastIndex]:\n print(f\"Error while attemping to determine index creation dates: {response[lastIndex]}\")\n sys.exit(1)\n\nr = response[lastIndex]\n\nindices = []\nfor index in r:\n try:\n if 'settings' in r[index]:\n settings = r[index]['settings']\n if 'index' in settings:\n meta = settings['index']\n if 'creation_date' in meta:\n creation_date = meta['creation_date']\n if int(creation_date) < int(minAgeFromEpoc):\n indices.append(index)\n else:\n sys.stderr.write(\"'creation_date' missing from index settings: %r\" % (meta))\n else:\n sys.stderr.write(\"'index' missing from setting: %r\" % (settings))\n else:\n sys.stderr.write(\"'settings' missing for %r\" % (index))\n except:\n e = sys.exc_info()[0]\n sys.stderr.write(\"Error trying to evaluate index from '%r': %r\" % (r,e))\nif writeIndex in indices:\n indices.remove(writeIndex)\nfor i in range(0, len(indices), 25):\n print(','.join(indices[i:i+25]))\n","sub_path":"indexmanagement-scripts-orig/getNext25Indices.py","file_name":"getNext25Indices.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"173104487","text":"# MIT LICENSE\n#\n# Copyright 1997 - 2020 by IXIA Keysight\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\nimport sys\nfrom ixnetwork_restpy.base import Base\nfrom ixnetwork_restpy.files import Files\n\nif sys.version_info >= (3, 5):\n from typing import List, Any, Union\n\n\nclass BroadcastDomainV6Vpws(Base):\n \"\"\"BGP V6 Broadcast Domain Configuration\n The BroadcastDomainV6Vpws class encapsulates a required broadcastDomainV6Vpws resource which will be retrieved from the server every time the property is accessed.\n \"\"\"\n\n __slots__ = ()\n _SDM_NAME = \"broadcastDomainV6Vpws\"\n _SDM_ATT_MAP = {\n \"Active\": \"active\",\n \"AdRouteLabel\": \"adRouteLabel\",\n \"AdvSrv6SidInIgp\": \"advSrv6SidInIgp\",\n \"AdvertiseSRv6SID\": \"advertiseSRv6SID\",\n \"ArgumentLength\": \"argumentLength\",\n \"BVlanId\": \"bVlanId\",\n \"BVlanPriority\": \"bVlanPriority\",\n \"BVlanTpid\": \"bVlanTpid\",\n \"BackupFlag\": \"backupFlag\",\n \"Count\": \"count\",\n \"DescriptiveName\": \"descriptiveName\",\n \"EnableVlanAwareService\": \"enableVlanAwareService\",\n \"EthernetTagId\": \"ethernetTagId\",\n \"FunctionLength\": \"functionLength\",\n \"FxcType\": \"fxcType\",\n \"GroupAddress\": \"groupAddress\",\n \"IncludeVpwsL2AttrExtComm\": \"includeVpwsL2AttrExtComm\",\n \"L2Mtu\": \"l2Mtu\",\n \"LocBlockLength\": \"locBlockLength\",\n \"LocNodeLength\": \"locNodeLength\",\n \"MvEnableTransposition\": \"mvEnableTransposition\",\n \"MvIncSrv6SidStructSsTlv\": \"mvIncSrv6SidStructSsTlv\",\n \"Name\": \"name\",\n \"NoOfMacPools\": \"noOfMacPools\",\n \"PrimaryPE\": \"primaryPE\",\n \"RemoteServiceId\": \"remoteServiceId\",\n \"RequireCW\": \"requireCW\",\n \"RootAddress\": \"rootAddress\",\n \"RsvpP2mpId\": \"rsvpP2mpId\",\n \"RsvpP2mpIdAsNumber\": \"rsvpP2mpIdAsNumber\",\n \"RsvpTunnelId\": \"rsvpTunnelId\",\n \"SendSRv6SIDOptionalInfo\": \"sendSRv6SIDOptionalInfo\",\n \"SenderAddressPRootNodeAddress\": \"senderAddressPRootNodeAddress\",\n \"Srv6EndpointBehavior\": \"srv6EndpointBehavior\",\n \"Srv6SIDOptionalInformation\": \"srv6SIDOptionalInformation\",\n \"Srv6SidFlags\": \"srv6SidFlags\",\n \"Srv6SidLoc\": \"srv6SidLoc\",\n \"Srv6SidLocLen\": \"srv6SidLocLen\",\n \"Srv6SidLocMetric\": \"srv6SidLocMetric\",\n \"Srv6SidReserved\": \"srv6SidReserved\",\n \"Srv6SidReserved1\": \"srv6SidReserved1\",\n \"Srv6SidReserved2\": \"srv6SidReserved2\",\n \"TranpositionLength\": \"tranpositionLength\",\n \"TranpositionOffset\": \"tranpositionOffset\",\n \"UsebVlan\": \"usebVlan\",\n \"VidNormalization\": \"vidNormalization\",\n }\n _SDM_ENUM_MAP = {}\n\n def __init__(self, parent, list_op=False):\n super(BroadcastDomainV6Vpws, self).__init__(parent, list_op)\n\n @property\n def PnTLVList(self):\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.pntlvlist_f29efa99695d122f75b5efd68698cd57.PnTLVList): An instance of the PnTLVList class\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n \"\"\"\n from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.pntlvlist_f29efa99695d122f75b5efd68698cd57 import (\n PnTLVList,\n )\n\n if len(self._object_properties) > 0:\n if self._properties.get(\"PnTLVList\", None) is not None:\n return self._properties.get(\"PnTLVList\")\n return PnTLVList(self)\n\n @property\n def Active(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Activate/Deactivate Configuration.\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"Active\"]))\n\n @property\n def AdRouteLabel(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): AD Route Label\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"AdRouteLabel\"]))\n\n @property\n def AdvSrv6SidInIgp(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Advertise SRv6 SID in IGP\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"AdvSrv6SidInIgp\"])\n )\n\n @property\n def AdvertiseSRv6SID(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Advertise SRv6 SID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"AdvertiseSRv6SID\"])\n )\n\n @property\n def ArgumentLength(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Argument Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"ArgumentLength\"])\n )\n\n @property\n def BVlanId(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): B VLAN ID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"BVlanId\"]))\n\n @property\n def BVlanPriority(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): B VLAN Priority\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"BVlanPriority\"]))\n\n @property\n def BVlanTpid(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): B VLAN TPID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"BVlanTpid\"]))\n\n @property\n def BackupFlag(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Backup Flag\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"BackupFlag\"]))\n\n @property\n def Count(self):\n # type: () -> int\n \"\"\"\n Returns\n -------\n - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group.\n \"\"\"\n return self._get_attribute(self._SDM_ATT_MAP[\"Count\"])\n\n @property\n def DescriptiveName(self):\n # type: () -> str\n \"\"\"\n Returns\n -------\n - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context.\n \"\"\"\n return self._get_attribute(self._SDM_ATT_MAP[\"DescriptiveName\"])\n\n @property\n def EnableVlanAwareService(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Enable VLAN Aware Service\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"EnableVlanAwareService\"])\n )\n\n @property\n def EthernetTagId(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Ethernet Tag ID. For VPWS, this acts as VPWS Service ID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"EthernetTagId\"]))\n\n @property\n def FunctionLength(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Function Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"FunctionLength\"])\n )\n\n @property\n def FxcType(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): FXC Type\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"FxcType\"]))\n\n @property\n def GroupAddress(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Group Address\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"GroupAddress\"]))\n\n @property\n def IncludeVpwsL2AttrExtComm(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Include VPWS Layer 2 Attributes Extended Community\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"IncludeVpwsL2AttrExtComm\"])\n )\n\n @property\n def L2Mtu(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): L2 MTU\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"L2Mtu\"]))\n\n @property\n def LocBlockLength(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Locator Block Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"LocBlockLength\"])\n )\n\n @property\n def LocNodeLength(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Locator Node Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"LocNodeLength\"]))\n\n @property\n def MvEnableTransposition(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Enable Transposition\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"MvEnableTransposition\"])\n )\n\n @property\n def MvIncSrv6SidStructSsTlv(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Include SRv6 SID Structure Sub-Sub TLV\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"MvIncSrv6SidStructSsTlv\"])\n )\n\n @property\n def Name(self):\n # type: () -> str\n \"\"\"\n Returns\n -------\n - str: Name of NGPF element, guaranteed to be unique in Scenario\n \"\"\"\n return self._get_attribute(self._SDM_ATT_MAP[\"Name\"])\n\n @Name.setter\n def Name(self, value):\n # type: (str) -> None\n self._set_attribute(self._SDM_ATT_MAP[\"Name\"], value)\n\n @property\n def NoOfMacPools(self):\n # type: () -> int\n \"\"\"\n Returns\n -------\n - number: Number of Mac Pools\n \"\"\"\n return self._get_attribute(self._SDM_ATT_MAP[\"NoOfMacPools\"])\n\n @NoOfMacPools.setter\n def NoOfMacPools(self, value):\n # type: (int) -> None\n self._set_attribute(self._SDM_ATT_MAP[\"NoOfMacPools\"], value)\n\n @property\n def PrimaryPE(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Primary PE\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"PrimaryPE\"]))\n\n @property\n def RemoteServiceId(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Remote Service ID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"RemoteServiceId\"])\n )\n\n @property\n def RequireCW(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Require CW\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"RequireCW\"]))\n\n @property\n def RootAddress(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Root Address\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"RootAddress\"]))\n\n @property\n def RsvpP2mpId(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): RSVP P2MP ID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"RsvpP2mpId\"]))\n\n @property\n def RsvpP2mpIdAsNumber(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): RSVP P2MP ID as Number\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"RsvpP2mpIdAsNumber\"])\n )\n\n @property\n def RsvpTunnelId(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): RSVP Tunnel ID\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"RsvpTunnelId\"]))\n\n @property\n def SendSRv6SIDOptionalInfo(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): If we need to advertise SRv6 SID Optional Information (Service Information sub-TLV) which is specified in next column(s)\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"SendSRv6SIDOptionalInfo\"])\n )\n\n @property\n def SenderAddressPRootNodeAddress(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Sender Address/P-Root Node Address\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self,\n self._get_attribute(self._SDM_ATT_MAP[\"SenderAddressPRootNodeAddress\"]),\n )\n\n @property\n def Srv6EndpointBehavior(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 Endpoint Behavior field Value for all routes in this Route Range\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6EndpointBehavior\"])\n )\n\n @property\n def Srv6SIDOptionalInformation(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Optional Information field Value (Service Information sub-TLV) for all routes in this Route Range\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SIDOptionalInformation\"])\n )\n\n @property\n def Srv6SidFlags(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Flags Value\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidFlags\"]))\n\n @property\n def Srv6SidLoc(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID. It consists of Locator, Func and Args\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidLoc\"]))\n\n @property\n def Srv6SidLocLen(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Locator Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidLocLen\"]))\n\n @property\n def Srv6SidLocMetric(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Locator Metric\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidLocMetric\"])\n )\n\n @property\n def Srv6SidReserved(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Reserved Value (SRv6 SID Service TLV Level)\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidReserved\"])\n )\n\n @property\n def Srv6SidReserved1(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Reserved1 Field for Service Information sub-TLV\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidReserved1\"])\n )\n\n @property\n def Srv6SidReserved2(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): SRv6 SID Reserved2 Field for Service Information sub-TLV\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"Srv6SidReserved2\"])\n )\n\n @property\n def TranpositionLength(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Transposition Length\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"TranpositionLength\"])\n )\n\n @property\n def TranpositionOffset(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): Transposition Offset\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"TranpositionOffset\"])\n )\n\n @property\n def UsebVlan(self):\n # type: () -> bool\n \"\"\"\n Returns\n -------\n - bool: Use B-VLAN\n \"\"\"\n return self._get_attribute(self._SDM_ATT_MAP[\"UsebVlan\"])\n\n @UsebVlan.setter\n def UsebVlan(self, value):\n # type: (bool) -> None\n self._set_attribute(self._SDM_ATT_MAP[\"UsebVlan\"], value)\n\n @property\n def VidNormalization(self):\n # type: () -> 'Multivalue'\n \"\"\"\n Returns\n -------\n - obj(ixnetwork_restpy.multivalue.Multivalue): VID Normalization\n \"\"\"\n from ixnetwork_restpy.multivalue import Multivalue\n\n return Multivalue(\n self, self._get_attribute(self._SDM_ATT_MAP[\"VidNormalization\"])\n )\n\n def update(self, Name=None, NoOfMacPools=None, UsebVlan=None):\n # type: (str, int, bool) -> BroadcastDomainV6Vpws\n \"\"\"Updates broadcastDomainV6Vpws resource on the server.\n\n This method has some named parameters with a type: obj (Multivalue).\n The Multivalue class has documentation that details the possible values for those named parameters.\n\n Args\n ----\n - Name (str): Name of NGPF element, guaranteed to be unique in Scenario\n - NoOfMacPools (number): Number of Mac Pools\n - UsebVlan (bool): Use B-VLAN\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n \"\"\"\n return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))\n\n def find(\n self,\n Count=None,\n DescriptiveName=None,\n Name=None,\n NoOfMacPools=None,\n UsebVlan=None,\n ):\n # type: (int, str, str, int, bool) -> BroadcastDomainV6Vpws\n \"\"\"Finds and retrieves broadcastDomainV6Vpws resources from the server.\n\n All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve broadcastDomainV6Vpws resources from the server.\n To retrieve an exact match ensure the parameter value starts with ^ and ends with $\n By default the find method takes no parameters and will retrieve all broadcastDomainV6Vpws resources from the server.\n\n Args\n ----\n - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group.\n - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context.\n - Name (str): Name of NGPF element, guaranteed to be unique in Scenario\n - NoOfMacPools (number): Number of Mac Pools\n - UsebVlan (bool): Use B-VLAN\n\n Returns\n -------\n - self: This instance with matching broadcastDomainV6Vpws resources retrieved from the server available through an iterator or index\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n \"\"\"\n return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))\n\n def read(self, href):\n \"\"\"Retrieves a single instance of broadcastDomainV6Vpws data from the server.\n\n Args\n ----\n - href (str): An href to the instance to be retrieved\n\n Returns\n -------\n - self: This instance with the broadcastDomainV6Vpws resources from the server available through an iterator or index\n\n Raises\n ------\n - NotFoundError: The requested resource does not exist on the server\n - ServerError: The server has encountered an uncategorized error condition\n \"\"\"\n return self._read(href)\n\n def get_device_ids(\n self,\n PortNames=None,\n Active=None,\n AdRouteLabel=None,\n AdvSrv6SidInIgp=None,\n AdvertiseSRv6SID=None,\n ArgumentLength=None,\n BVlanId=None,\n BVlanPriority=None,\n BVlanTpid=None,\n BackupFlag=None,\n EnableVlanAwareService=None,\n EthernetTagId=None,\n FunctionLength=None,\n FxcType=None,\n GroupAddress=None,\n IncludeVpwsL2AttrExtComm=None,\n L2Mtu=None,\n LocBlockLength=None,\n LocNodeLength=None,\n MvEnableTransposition=None,\n MvIncSrv6SidStructSsTlv=None,\n PrimaryPE=None,\n RemoteServiceId=None,\n RequireCW=None,\n RootAddress=None,\n RsvpP2mpId=None,\n RsvpP2mpIdAsNumber=None,\n RsvpTunnelId=None,\n SendSRv6SIDOptionalInfo=None,\n SenderAddressPRootNodeAddress=None,\n Srv6EndpointBehavior=None,\n Srv6SIDOptionalInformation=None,\n Srv6SidFlags=None,\n Srv6SidLoc=None,\n Srv6SidLocLen=None,\n Srv6SidLocMetric=None,\n Srv6SidReserved=None,\n Srv6SidReserved1=None,\n Srv6SidReserved2=None,\n TranpositionLength=None,\n TranpositionOffset=None,\n VidNormalization=None,\n ):\n \"\"\"Base class infrastructure that gets a list of broadcastDomainV6Vpws device ids encapsulated by this object.\n\n Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object.\n\n Args\n ----\n - PortNames (str): optional regex of port names\n - Active (str): optional regex of active\n - AdRouteLabel (str): optional regex of adRouteLabel\n - AdvSrv6SidInIgp (str): optional regex of advSrv6SidInIgp\n - AdvertiseSRv6SID (str): optional regex of advertiseSRv6SID\n - ArgumentLength (str): optional regex of argumentLength\n - BVlanId (str): optional regex of bVlanId\n - BVlanPriority (str): optional regex of bVlanPriority\n - BVlanTpid (str): optional regex of bVlanTpid\n - BackupFlag (str): optional regex of backupFlag\n - EnableVlanAwareService (str): optional regex of enableVlanAwareService\n - EthernetTagId (str): optional regex of ethernetTagId\n - FunctionLength (str): optional regex of functionLength\n - FxcType (str): optional regex of fxcType\n - GroupAddress (str): optional regex of groupAddress\n - IncludeVpwsL2AttrExtComm (str): optional regex of includeVpwsL2AttrExtComm\n - L2Mtu (str): optional regex of l2Mtu\n - LocBlockLength (str): optional regex of locBlockLength\n - LocNodeLength (str): optional regex of locNodeLength\n - MvEnableTransposition (str): optional regex of mvEnableTransposition\n - MvIncSrv6SidStructSsTlv (str): optional regex of mvIncSrv6SidStructSsTlv\n - PrimaryPE (str): optional regex of primaryPE\n - RemoteServiceId (str): optional regex of remoteServiceId\n - RequireCW (str): optional regex of requireCW\n - RootAddress (str): optional regex of rootAddress\n - RsvpP2mpId (str): optional regex of rsvpP2mpId\n - RsvpP2mpIdAsNumber (str): optional regex of rsvpP2mpIdAsNumber\n - RsvpTunnelId (str): optional regex of rsvpTunnelId\n - SendSRv6SIDOptionalInfo (str): optional regex of sendSRv6SIDOptionalInfo\n - SenderAddressPRootNodeAddress (str): optional regex of senderAddressPRootNodeAddress\n - Srv6EndpointBehavior (str): optional regex of srv6EndpointBehavior\n - Srv6SIDOptionalInformation (str): optional regex of srv6SIDOptionalInformation\n - Srv6SidFlags (str): optional regex of srv6SidFlags\n - Srv6SidLoc (str): optional regex of srv6SidLoc\n - Srv6SidLocLen (str): optional regex of srv6SidLocLen\n - Srv6SidLocMetric (str): optional regex of srv6SidLocMetric\n - Srv6SidReserved (str): optional regex of srv6SidReserved\n - Srv6SidReserved1 (str): optional regex of srv6SidReserved1\n - Srv6SidReserved2 (str): optional regex of srv6SidReserved2\n - TranpositionLength (str): optional regex of tranpositionLength\n - TranpositionOffset (str): optional regex of tranpositionOffset\n - VidNormalization (str): optional regex of vidNormalization\n\n Returns\n -------\n - list(int): A list of device ids that meets the regex criteria provided in the method parameters\n\n Raises\n ------\n - ServerError: The server has encountered an uncategorized error condition\n \"\"\"\n return self._get_ngpf_device_ids(locals())\n","sub_path":"ixnetwork_restpy/testplatform/sessions/ixnetwork/topology/broadcastdomainv6vpws_59a832939f2a9320bf834055352368fd.py","file_name":"broadcastdomainv6vpws_59a832939f2a9320bf834055352368fd.py","file_ext":"py","file_size_in_byte":29658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"189684994","text":"import re\nimport matplotlib.pyplot as plt\nfrom pyspark import SparkConf\nfrom pyspark import SparkContext\n\n#\n# Create the SparkContext\n#\nconf = SparkConf().setAppName('lfreq')\nsc = SparkContext(conf=conf)\n\ndef process_line(l):\n return re.sub(\"[^a-z]\",\"\", l.lower())\n\nrddWords = sc.textFile('wnp.txt')\\\n .flatMap( lambda line: process_line(line) )\\\n .map( lambda x: (x,1) )\\\n .reduceByKey( lambda a,b: a+b )\\\n .sortBy(lambda x: x[1],ascending=False)\n\nfoo = rddWords.collect()\n\n#\n# Plot the data\n#\nxticks=[]\nxdata=[]\nydata=[]\nn=0\nfor tup in foo:\n xticks.append(tup[0])\n ydata.append(tup[1])\n xdata.append(n)\n n=n+1\n\nplt.bar(xdata,ydata)\nplt.xticks(xdata,xticks)\nplt.show()\n\nexit(0)\n\n","sub_path":"lfreq.py","file_name":"lfreq.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"249743866","text":"from .single_tour_op import Route, Node, SingleTourOrienteering\n\n\nclass MaxMinOrienteering:\n def __init__(self, locations, time_budget, required_tours, start_end_node, target_importance):\n self.locations = locations\n self.time_budget = time_budget\n self.required_tours = required_tours\n self.start_end_node = start_end_node\n self.target_importance = target_importance\n\n def compute_path(self):\n # Stage 1\n tour_list = []\n tau_list = []\n for location_attribute in self.locations.get_locations_attributes():\n if location_attribute[3] > self.target_importance:\n route = Route()\n route.append(self.start_end_node)\n route.append(Node(location_attribute))\n tour_list.append(route)\n tau_list.append(route.create_tour_visit_time())\n del self.locations[location_attribute[0]]\n if len(tour_list) > self.required_tours:\n return tour_list, tau_list\n\n # Stage 2\n for i in range(self.required_tours - len(tour_list ) + 1):\n sto = SingleTourOrienteering(self.locations, self.time_budget, self.start_end_node)\n tour, tau = sto.compute_path()\n tour, tar = sto.truncate_tour(tour, tau)\n if tour.calculate_tour_utility >= self.target_importance:\n tour_list.append(tour)\n tau_list.append(tau)\n for node in tour:\n del self.locations[node.lid]\n\n # Stage 3\n return tour_list, tau_list\n\n def truncate_tour(self, tour, tau):\n for id, node in enumerate(tour):\n del tour[id]\n del tau[id]\n if tour.calculate_tour_utility() <= 2*self.target_importance:\n break\n return tour, tau\n\n\n","sub_path":"tripleisure/max_min_op/max_min_op.py","file_name":"max_min_op.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"577992370","text":"import ast\nfrom ast import *\nimport json\nimport sys\nimport collections\nfrom PyCS.utils.InfoClass import InfoClass\nfrom PyCS.utils.find_show_code import find_show_code\n\nsub_node = []\n\n\ndef doc(node, depth=1):\n '''\n DOC: depth of closure\n '''\n max_depth = 0\n for n in ast.walk(node):\n sub_node.append(n)\n for t_n in node.body:\n if isinstance(t_n, FunctionDef):\n max_depth = max(doc(t_n, depth+1), max_depth)\n sub_node.remove(node)\n return max_depth + 1\n\n\ndef is_lsc(node):\n with open('PyCS/static/json/configure.json') as conf_file:\n conf = json.load(conf_file)\n THRESHOLD_LSC = conf[\"LSC\"][\"DOC\"]\n return doc(node) >= THRESHOLD_LSC\n\n\ndef detect(file, content, codes):\n # DOC >= 3\n root = ast.parse(content)\n for n in ast.walk(root):\n if isinstance(n, FunctionDef):\n if n not in sub_node:\n if is_lsc(n):\n yield result_report(n, file, codes)\n else:\n sub_node.remove(n)\n\n\ndef result_report(node, file, codes):\n return InfoClass(\n 'Long Scope Chaining',\n node.lineno,\n node.col_offset + 1,\n file,\n '',\n 'a method or a function that is multiply-nested. '\n 'Try to construct it.',\n find_show_code(codes, node.lineno)\n )\n\nif __name__ == '__main__':\n detect('temp.py')\n","sub_path":"PyCS/utils/LSCDetect.py","file_name":"LSCDetect.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"401207992","text":"from lxml import etree\nimport time\nimport urllib2\nfrom core.proxy import ProxyFactory\n\nclass Xicidaili(ProxyFactory):\n name = 'xicidaili'\n def FetchProxies(self):\n user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n headers = { 'User-Agent' : user_agent }\n baseURL = 'http://www.xicidaili.com/nn/'\n proxies = []\n for page in range(1, 101):\n req = urllib2.Request(baseURL + str(page), None, headers)\n resp = urllib2.urlopen(req)\n content = resp.read()\n resp.close()\n# with open('r.txt', 'w') as c:\n# c.write(content)\n tree = etree.HTML(content)\n ipNodes = tree.xpath('//*[@id=\"ip_list\"]/tr/td[3]')\n portNodes = tree.xpath('//*[@id=\"ip_list\"]/tr/td[4]')\n typeNodes = tree.xpath('//*[@id=\"ip_list\"]/tr/td[7]')\n for i,t in enumerate(typeNodes):\n if(t.text.strip() == 'HTTP'):\n #print ipNodes[i].text.strip() + \":\" + portNodes[i].text.strip()\n proxies += [\"http://{0}:{1}\".format(ipNodes[i].text.strip(), portNodes[i].text.strip())]\n\n print(\"{0} fetched\".format(len(proxies)))\n return proxies\n\nif __name__ == '__main__':\n \n# for page in range(20, 50):\n start = time.time()\n p = Xicidaili()\n p.Run()\n end = time.time()\n print(\"total time:\", end - start, \"s\")\n #print(pf.proxyPairs)\n","sub_path":"proxy/xicidaili.py","file_name":"xicidaili.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"373214081","text":"# 导入Flask类\n\nimport json\nimport time\nimport os\nimport logging\nimport sys\nimport collections\nimport configparser\nfrom flask import Flask, jsonify, request\nimport LAC\nimport gensim\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport sklearn.utils\nimport sklearn.model_selection\n#import happybase\nimport joblib\n#from IPython.core.interactiveshell import InteractiveShell\n#InteractiveShell.ast_node_interactivity = \"all\" \nfrom sklearn.cluster import KMeans \nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\n#from bayes_opt import BayesianOptimization\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.feature_selection import RFE\nfrom keras.models import load_model\n\nAPP_DIR=os.path.dirname(os.path.abspath('__file__'))\nsys.path.append(APP_DIR)\n\nconfig_ini_dict=configparser.ConfigParser()\nconfig_ini_dict.read(os.path.join(APP_DIR,\"config.ini\"))\nlogging.info(config_ini_dict)\n# 实例化,可视为固定格式\napp =Flask(__name__)\n\ndef pre_chuli(data_list_list,type_list):\n title_tokenize_list = []\n #age_list = []\n for i in range(len(data_list_list)):\n # age = temp_function(int(df.loc[index,\"age\"]))\n temp_text_list = []\n for j in range(10):\n c_text_list = [data_list_list[i][j][\"title\"],\"\",data_list_list[i][j][\"content\"][:512]]\n temp_text_list.append(c_text_list) \n title_tokenize_list.append(temp_text_list)\n with open(config_ini_dict[\"file\"][\"data_jsonl\"],\"w\",encoding='UTF-8') as f:\n for content_tokenize in zip(title_tokenize_list):\n f.write(json.dumps({\"all_content_tokenize\":content_tokenize},ensure_ascii=False) + \"\\n\")\n return type_list\nAPP_DIR = os.path.dirname(os.path.realpath('__file__'))\n\ndef trans_gensim_word2vec2tf_embedding(word2vector_file_path:str):\n \"\"\"把gensim的word2vec结果转化为tf.keras.layers.Embedding需要的结果\n \"\"\"\n\n word2vec_model = gensim.models.Word2Vec.load(word2vector_file_path)\n\n #所有的词\n word_list = [word for word, word_info in word2vec_model.wv.vocab.items()]\n\n #词到index的映射\n word2index_dict = {\"\": 0, \"\":1}\n\n #保存特殊词的padding\n specical_word_count = len(word2index_dict)\n\n #词到词向量的映射\n word2vector_dict = {}\n\n #初始化embeddings_matrix\n\n embeddings_matrix = np.zeros((len(word_list) + specical_word_count, word2vec_model.vector_size))\n #初始化unk为-1,1分布\n embeddings_matrix[word2index_dict[\"\"]] = (1 / np.sqrt(len(word_list) + specical_word_count) * (2 * np.random.rand(word2vec_model.vector_size) - 1))\n\n for i,word in enumerate(word_list):\n #从0开始\n word_index = i + specical_word_count\n word2index_dict[str(word)] = word_index\n word2vector_dict[str(word)] = word2vec_model.wv[word] # 词语:词向量\n embeddings_matrix[word_index] = word2vec_model.wv[word] # 词向量矩阵\n print()\n\n #写入文件\n with open(os.path.join(APP_DIR,\"data\",\"word2index.json\"),\"w\",encoding=\"utf8\") as f:\n json.dump(word2index_dict,f,ensure_ascii=False)\n\n return embeddings_matrix,word2vector_dict,word2index_dict\ndef trans2index(word2index_dict,word):\n \"\"\"转换\"\"\"\n if word in word2index_dict:\n return word2index_dict[word]\n else:\n if \"\" in word2index_dict:\n return word2index_dict[\"\"]\n else:\n raise ValueError(\"没有这个值,请检查\")\n\n\ndef trans_data2tf_data(data_file_path:str,x_max_length:int=None,word2index_dict=None):\n \"\"\"把data文件转化为tf.data\n \"\"\"\n\n # tag2index_dict = {}\n # tag_index_count = len(tag2index_dict)\n lac = LAC.LAC(mode=\"seg\")\n\n df = pd.read_csv(data_file_path)\n\n x_list = []\n for doc in df[\"content\"]:\n word_list = lac.run(doc)\n x_list.append([trans2index(word2index_dict,word) for word in word_list])\n x_npa = np.array(x_list)\n\n\n if not x_max_length:\n x_max_length0 = np.max(np.array([len(v) for v in x_list]))\n x_max_length = int(np.max(np.percentile(np.array([len(v) for v in x_list]),99.7)))\n print(\"数据集中最长的句子长度为:{},设定的最长的句子长度为:{}\".format(x_max_length0,x_max_length))\n\n x_npa = tf.keras.preprocessing.sequence.pad_sequences(x_npa,maxlen=x_max_length,dtype=np.int32,truncating=\"post\", padding='post',value=0)\n\n return x_npa\ndef trans_tokenize_data2tf_data(data_file_path:str,x_max_length:int=None,word2index_dict=None):\n \"\"\"把已经分好词的data文件转化为tf.data\n \"\"\"\n\n # tag2index_dict = {}\n# tag_index_count = len(tag2index_dict)\n lac = LAC.LAC(mode=\"seg\")\n\n x_list = []\n # y_list = []\n with open(data_file_path) as f:\n for line in f:\n temp_dict = json.loads(line.strip())\n word_list = temp_dict[\"content_tokenize\"]\n x_list.append([trans2index(word2index_dict,word) for word in word_list])\n x_npa = np.array(x_list)\n\n# print(\"x_list[:1]:{}\".format(x_list[:1]))\n\n if not x_max_length:\n x_max_length0 = np.max(np.array([len(v) for v in x_list]))\n x_max_length = int(np.max(np.percentile(np.array([len(v) for v in x_list]),99.7)))\n print(\"数据集中最长的句子长度为:{},设定的最长的句子长度为:{}\".format(x_max_length0,x_max_length))\n\n x_npa = tf.keras.preprocessing.sequence.pad_sequences(x_npa,maxlen=x_max_length,dtype=np.int32,truncating=\"post\", padding='post',value=0)\n # print(\"x_npa[:1]:{}\".format(x_npa[:1]))\n # print(\"x_npa.shape = {}\".format(x_npa.shape))\n return x_npa\n\n\ndef trans_multi_input_tokenize_data2npa(data_file_path:str,x_max_length:int=None,word2index_dict=None):\n \"\"\"把已经分好词的data文件转化为tf.data , 多输入版本\n \"\"\"\n x_list = []\n with open(data_file_path) as f:\n for line in f:\n temp_dict = json.loads(line.strip())\n text_tokenize_list = temp_dict[\"all_content_tokenize\"]\n text_tokenize_list = sum(text_tokenize_list,[])\n x_list.append([[trans2index(word2index_dict,word) for word in word_list] for word_list in text_tokenize_list])\n\n # print(\"x_list[:1]:{}\".format(x_list[:1]))\n\n if not x_max_length:\n x_max_length0 = np.max(np.array([len(v) for v in x_list]))\n x_max_length = int(np.max(np.percentile(np.array([len(v) for v in x_list]),99.7)))\n # print(\"数据集中最长的句子长度为:{},设定的最长的句子长度为:{}\".format(x_max_length0,x_max_length))\n \n for i in range(len(x_list)):\n x_list[i] = tf.keras.preprocessing.sequence.pad_sequences(x_list[i],maxlen=x_max_length,dtype=np.int32,truncating=\"post\", padding='post',value=0)\n x_npa = np.array(x_list,dtype=np.int32)\n# x_npa_position = x_npa\n\n return x_npa\n\nAPP_DIR = os.path.dirname(os.path.realpath('__file__'))\nif not os.path.exists(os.path.join(APP_DIR,\"data\")):\n os.makedirs(os.path.join(APP_DIR,\"data\"))\n\ndef split_train_eval_test_dataset(dataset):\n \"\"\"区分训练验证测试集\n \"\"\"\n dataset_size = tf.data.experimental.cardinality(dataset).numpy()\n # print(\"总共有数据{}条\".format(dataset_size))\n dataset = dataset.shuffle(dataset_size,seed=1)\n train_size = int(0.6 * dataset_size)\n eval_size = int(0.2 * dataset_size)\n test_size = int(0.2 * dataset_size)\n\n train_dataset = dataset.take(train_size)\n test_dataset = dataset.skip(train_size)\n eval_dataset = test_dataset.skip(eval_size)\n test_dataset = test_dataset.take(test_size)\n return train_dataset.prefetch(tf.data.experimental.AUTOTUNE), \\\n eval_dataset.prefetch(tf.data.experimental.AUTOTUNE), \\\n test_dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\ndef split_train_eval_test_npa(x_npa,y_npa):\n x_train,x_test,y_train,y_test = sklearn.model_selection.train_test_split(x_npa, y_npa, test_size=0.2, random_state=24)\n return x_train,y_train,x_test,y_test\n\ndef data_mining(x_npa): \n x_npa = x_npa.reshape(len(x_npa),5120)\n x_npa = pd.DataFrame(x_npa)\n x_npa.columns = [*[\"c{}\".format(v) for v in range(5120)]]\n age_data = x_npa.T\n df_22 = age_data[0:999]\n # rank0_1000 = pd.read_csv('../data/predict_user_attribute20200911/raw_data/user_profile/age/rank0_1000.csv')\n rank_temp = config_ini_dict[\"file\"][\"rank0_1000\"]\n rank_temp = rank_temp.split(\",\")\n rank0_1000 = []\n for i in rank_temp:\n b = int(i)\n rank0_1000.append(b)\n rank0_1000 = pd.DataFrame(rank0_1000)\n rank0_1000.columns = ['rank']\n df0_1000 = pd.merge(rank0_1000,df_22,on = rank0_1000.index)\n df0_1000 = df0_1000.drop('key_0',axis = 1)\n df0_1000 = df0_1000.groupby(df0_1000.index).filter(lambda x:float(x['rank'])==1)\n #df_22 = df_22.T\n df_22 = age_data[999:1999]\n# rank1000_2000 = pd.read_csv('../data/predict_user_attribute20200911/raw_data/user_profile/age/rank1000_2000.csv')\n rank_temp1 = config_ini_dict[\"file\"][\"rank1000_2000\"]\n rank_temp1 = rank_temp1.split(\",\")\n rank1000_2000 = []\n for i in rank_temp1:\n b = int(i)\n rank1000_2000.append(b)\n rank1000_2000 = pd.DataFrame(rank1000_2000)\n rank1000_2000.columns = ['rank']\n df1000_2000 = pd.merge(rank1000_2000,df_22,on = rank1000_2000.index)\n df1000_2000 = df1000_2000.drop('key_0',axis = 1)\n df1000_2000 = df1000_2000.groupby(df1000_2000.index).filter(lambda x:float(x['rank'])==1)\n df_22 = age_data[1999:2999]\n #df_22 = df_22.T\n# rank2000_3000 = pd.read_csv('../data/predict_user_attribute20200911/raw_data/user_profile/age/rank2000_3000.csv')\n# rank2000_3000 = rank2000_3000.drop('Unnamed: 0',axis = 1)\n rank_temp2 = config_ini_dict[\"file\"][\"rank2000_3000\"]\n rank_temp2 = rank_temp2.split(\",\")\n rank2000_3000 = []\n for i in rank_temp1:\n b = int(i)\n rank2000_3000.append(b)\n rank2000_3000 = pd.DataFrame(rank2000_3000)\n rank2000_3000.columns = ['rank']\n df2000_3000 = pd.merge(rank2000_3000,df_22,on = rank2000_3000.index)\n df2000_3000 = df2000_3000.drop('key_0',axis = 1)\n df2000_3000 = df2000_3000.groupby(df2000_3000.index).filter(lambda x:float(x['rank'])==1)\n df_22 = age_data[2998:5121]\n #df_22 = df_22.T\n# rank3000_5122 = pd.read_csv('../data/predict_user_attribute20200911/raw_data/user_profile/age/rank3000_5122.csv')\n# rank3000_5122 = rank3000_5122.drop('Unnamed: 0',axis = 1)\n rank_temp3 = config_ini_dict[\"file\"][\"rank3000_5122\"]\n rank_temp3 = rank_temp3.split(\",\")\n rank3000_5122 = []\n for i in rank_temp3:\n b = int(i)\n rank3000_5122.append(b)\n rank3000_5122 = pd.DataFrame(rank3000_5122)\n rank3000_5122.columns = ['rank']\n df3000_5122 = pd.merge(rank3000_5122,df_22,on = rank3000_5122.index)\n df3000_5122 = df3000_5122.drop('key_0',axis = 1)\n df3000_5122 = df3000_5122.groupby(df3000_5122.index).filter(lambda x:float(x['rank'])==1)\n x_drop_fea1 = pd.concat([df0_1000, df1000_2000], axis=0, ignore_index=True)\n x_drop_fea1 = pd.concat([x_drop_fea1, df2000_3000], axis=0, ignore_index=True)\n x_drop_fea1 = pd.concat([x_drop_fea1, df3000_5122], axis=0, ignore_index=True)\n x_drop_fea1 = x_drop_fea1.drop('rank',axis = 1)\n# rank_100 = pd.read_csv('../data/predict_user_attribute20200911/raw_data/user_profile/age/rank_100.csv')\n# rank_100 = rank_100.drop('Unnamed: 0',axis = 1)\n rank_temp4 = config_ini_dict[\"file\"][\"rank_100\"]\n rank_temp4 = rank_temp4.split(\",\")\n rank_100 = []\n for i in rank_temp4:\n b = int(i)\n rank_100.append(b)\n rank_100 = pd.DataFrame(rank_100)\n rank_100.columns = ['rank']\n x_drop_100 = pd.merge(rank_100,x_drop_fea1,on = rank_100.index)\n x_drop_100 = x_drop_100.drop('key_0',axis = 1)\n x_drop_100 = x_drop_100.groupby(x_drop_100.index).filter(lambda x:float(x['rank'])==1)\n x_drop_100 = x_drop_100.drop('rank',axis = 1)\n x_drop_100 = x_drop_100.T\n ss = StandardScaler()\n x_drop1_100 = ss.fit_transform(x_drop_100)\n x_drop1_100 = pd.DataFrame(x_drop1_100)\n return x_drop1_100\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32,\n np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\n# route()方法用于设定路由;类似spring路由配置\n@app.route('/test_1/',methods=['post','get'])\ndef predict():\n \n if request.method == 'POST':\n start = time.time()\n content_list = request.json['data_list_list']\n type_list = request.json['type_list']\n # print(content_id_list)\n pre_chuli(content_list,type_list)\n result = {\"result\": []}\n \n d = dict()\n for type_1 in type_list:\n if type_1 == \"age\":\n pre_age = model_age.predict(x_drop1_100)\n d['age'] = pre_age.tolist()\n elif type_1 == \"position\":\n pre_position = model_position.predict(x_drop1_100)\n d['position'] = pre_position.tolist()\n elif type_1 == 'trade':\n pre_trade = model_trade.predict(x_drop1_100)\n d['trade'] = pre_trade.tolist()\n else:\n pre_gender = model_gender.predict(x_drop1_100)\n d['gender'] = pre_trade.tolist()\n # pre = model.predict(x_drop1_100)\n result[\"result\"].append(d)\n # print(result)\n # pre = pre.tolist()\n dic_age = {0:'36~45',1:'30~35',2:'26~29',\n 3:'~20',4:'46~50',5:'21~25',6:'50~'}\n dic_position = {0:'企业业务决策层',1:'企业普通员工',2:'企业CEO',3:'企业一般管理人员',\n 4:'其他',5:'在校学生',6:'事业单位员工'}\n dic_trade = {0:'金融',\n 1:'IT/移动互联网',\n 2:'其他',\n 3:'制造业',\n 4:'房地产',\n 5:'零售消费',\n 6:'汽车',\n 7:'电商',\n 8:'IOT',\n 9:'游戏',\n 10:'医疗'}\n dic_gender = {0:'男',\n 1:'女',\n 2:'aaaf'}\n out_list = []\n for type_2 in type_list:\n if type_2 == 'age':\n for i in result[\"result\"][0]['age']:\n out_list.append(dic_age[i])\n if type_2 == 'position':\n for i in result['result'][0]['position']:\n out_list.append(dic_position[i])\n if type_2 == 'trade':\n for i in result['result'][0]['trade']:\n out_list.append(dic_trade[i])\n if type_2 == 'gender':\n for i in result['result'][0]['gender']:\n out_list.append(dic_gender[i])\n end = time.time()\n print(\"time: {:.2f} s\".format(end - start))\n return jsonify({\"result\" : out_list})\n \n \nif __name__ == '__main__':\n filepath_age = config_ini_dict[\"file\"][\"filepath_age\"]\n #filepath_position = \"../code/model_position\"\n data_jsonl = config_ini_dict[\"file\"][\"data_jsonl\"]\n word2vector_file_path = config_ini_dict[\"file\"][\"word2vector_file_path\"]\n model_age = joblib.load(filepath_age)\n# tf.keras.models.Model\n model_position = joblib.load(filepath_age)\n model_trade = joblib.load(filepath_age)\n model_gender = joblib.load(filepath_age)\n input_number = 10\n sentence_maxlen = 512 \n embedding_matrix,word2vector_dict,word2index_dict = trans_gensim_word2vec2tf_embedding(word2vector_file_path)\n vocab_size,embedding_dim = embedding_matrix.shape\n x_npa = trans_multi_input_tokenize_data2npa(data_jsonl,sentence_maxlen,word2index_dict) \n x_npa_position = x_npa\n x_drop1_100 = data_mining(x_npa) \n # app.run(host, port, debug, options)\n # 默认值:host=\"127.0.0.1\", port=5000, debug=False\n app.run(host=\"0.0.0.0\", port=8888) \n ","sub_path":"predict_user_attribute/age/new_improve_one/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"200881693","text":"import datetime\n\nfrom project.server.helpers.encrypter import encrypt_password\nfrom project.server.managers.database import db\n\n\nclass Models(db.Model):\n \"\"\" Models Model for storing model related details \"\"\"\n __tablename__ = \"ai_models\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n updated_on = db.Column(db.DateTime(), nullable=False)\n model_path = db.Column(db.String(255), nullable=False)\n camera_id = db.Column(db.String(255), nullable=False)\n dataset = db.Column(db.String(255), nullable=False)\n\n def __init__(self, updated_on, model_path, camera_id, dataset):\n self.updated_on = updated_on\n self.model_path = model_path\n self.camera_id = camera_id\n self.dataset = dataset\n\n def from_json(self, json):\n self.id = json.get('user_id', None)\n self.updated_on = json.get('updated_on', None)\n self.model_path = json.get('model_path', None)\n self.camera_id = json.get('camera_id', None)\n self.dataset = json.get('dataset', None)\n return self\n\n def to_dictionary(self):\n obj = {\n 'model_id': self.id,\n 'updated_on': self.updated_on,\n 'model_path': self.model_path,\n 'camera_id': self.camera_id,\n 'dataset': self.dataset\n }\n return obj\n","sub_path":"project/server/models/ai_models.py","file_name":"ai_models.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"86593555","text":"# coding=utf-8\nfrom utils import load_vocab, read_corpus, load_model, save_model,Tjson\nfrom tqdm import tqdm\n# # return [\"O\", \"B-PER\", \"I-PER\", \"B-ORG\", \"I-ORG\", \"B-LOC\", \"I-LOC\", \"[CLS]\",\"[SEP]\"]\n# return [\"O\", \"B-PER\", \"I-PER\", \"B-ORG\", \"I-ORG\", \"B-LOC\", \"I-LOC\", \"X\",\"[CLS]\",\"[SEP]\"]\nimport Terry_toolkit as tkit\n\n\n# def \n\n# for \n\ndef ner_rebulid():\n \"\"\"\n 将原有数据转化为标记数据\n \"\"\"\n new_train=Tjson(file_path=\"data/train.json\")\n new_dev=Tjson(file_path=\"data/dev.json\")\n files=[\"data/o/train.json\",\"data/o/dev.json\"]\n data=[]\n for file in files:\n for line in Tjson(file_path=file).load():\n # print(\"line\",line['label'])\n new_label={}\n for i,label in enumerate(line['label']):\n one={}\n new_label[i]=label\n if i==0:\n a={'type':\"实体\",'num':[]}\n\n if label==\"B-ORG\":\n\n # 在为O时候处理\n if len(a['num'])>=2:\n for key,i_n in enumerate(a['num']):\n if key==0:\n new_label[i_n]=\"B-\"+a['type']\n elif key==len(a['num'])-1:\n new_label[i_n]=\"E-\"+a['type']\n else:\n new_label[i_n]=\"M-\"+a['type']\n elif len(a['num'])==1:\n new_label[a['num'][0]]=\"S-\"+a['type']\n a={'type':\"实体\",'num':[i]}\n\n\n elif label==\"I-ORG\":\n a['num'].append(i)\n elif label==\"B-PER\":\n\n # 在为O时候处理\n if len(a['num'])>=2:\n for key,i_n in enumerate(a['num']):\n if key==0:\n new_label[i_n]=\"B-\"+a['type']\n elif key==len(a['num'])-1:\n new_label[i_n]=\"E-\"+a['type']\n else:\n new_label[i_n]=\"M-\"+a['type']\n elif len(a['num'])==1:\n new_label[a['num'][0]]=\"S-\"+a['type']\n a={'type':\"实体\",'num':[i]}\n\n\n elif label==\"I-PER\":\n a['num'].append(i)\n elif label==\"B-LOC\":\n # 在为O时候处理\n if len(a['num'])>=2:\n for key,i_n in enumerate(a['num']):\n if key==0:\n new_label[i_n]=\"B-\"+a['type']\n elif key==len(a['num'])-1:\n new_label[i_n]=\"E-\"+a['type']\n else:\n new_label[i_n]=\"M-\"+a['type']\n elif len(a['num'])==1:\n new_label[a['num'][0]]=\"S-\"+a['type'] \n a={'type':\"地��\",'num':[i]}\n\n\n elif label==\"I-LOC\":\n a['num'].append(i)\n else:\n # 在为O时候处理\n if len(a['num'])>=2:\n for key,i_n in enumerate(a['num']):\n if key==0:\n new_label[i_n]=\"B-\"+a['type']\n elif key==len(a['num'])-1:\n new_label[i_n]=\"E-\"+a['type']\n else:\n new_label[i_n]=\"M-\"+a['type']\n elif len(a['num'])==1:\n new_label[a['num'][0]]=\"S-\"+a['type']\n\n # a={'type':\"实体\",'num':[i]}\n labels=[]\n # print(new_label)\n tags={}\n for l in new_label:\n labels.append(new_label[l])\n # print(new_label[l])\n tags[new_label[l]]=0\n if len(tags)>1:\n one={\"text\":line[\"text\"], \"label\":labels}\n # print(one)\n data.append(one)\n f=int(len(data)*0.85)\n new_train.save(data[:f])\n new_dev.save(data[f:])\n\n\n\ndef _read_data( input_file):\n \"\"\"Reads a BIO data.\"\"\"\n max_length=100\n # num=max_length #定义每组包含的元素个数\n with open(input_file) as f:\n lines = []\n words = []\n labels = []\n stop = [\"。\",\"!\",\"!\"]\n for line in f:\n contends = line.strip()\n \n # print(len(line.strip().split(' ')))\n word = line.strip().split(' ')[0]\n label = line.strip().split(' ')[-1]\n\n if contends.startswith(\"-DOCSTART-\"):\n words.append('')\n continue\n # if len(contends) == 0 and words[-1] == '。':\n if len(contends) == 0:\n # l = ' '.join([label for label in labels if len(label) > 0])\n # w = ' '.join([word for word in words if len(word) > 0])\n l=[label for label in labels if len(label) > 0]\n w = [word for word in words if len(word) > 0]\n if l==w:\n # print('xian')\n pass\n else:\n w_one=[]\n l_one=[]\n # n=0\n tags={}\n for i,it in enumerate(w):\n #基于句子分段\n if it in stop:\n w_one.append(w[i])\n l_one.append(l[i])\n tags[l[i]]=0\n # 如果标记内容过少则忽略\n if len(tags)>1:\n lines.append([l_one, w_one])\n tags={}\n w_one=[]\n l_one=[]\n elif i==len(w)-1:\n if len(tags)>1:\n lines.append([l_one, w_one])\n tags={}\n w_one=[]\n l_one=[]\n else:\n tags[l[i]]=0\n w_one.append(w[i])\n l_one.append(l[i])\n \n # # 如果内容过长自动分段\n # if len(l)> max_length:\n # for i in range(0,len(l),max_length):\n # # print l[i:i+num]\n # lines.append([l[i:i+max_length], w[i:i+max_length]])\n # else:\n # lines.append([l, w])\n words = []\n labels = []\n continue\n words.append(word)\n labels.append(label)\n return lines\n\n\ndef build_ner(input_file,path='./',tags=None,type='all'):\n d=_read_data(input_file)\n # tjson=Tjson(file_path=train_file)\n tjson_save=Tjson(file_path=path+\"train.json\")\n dev_json_save=Tjson(file_path=path+\"dev.json\")\n data=[]\n if tags==None:\n tags={ \"\":1,\"O\":1,\"\":1,\"\":1}\n\n for item in tqdm(d):\n \n text= item[0]\n # print(text)\n # print(item['spo_list'])\n # predicate={}\n # for n in item['spo_list']:\n # predicate[n['predicate']]=[]\n \n # print(label)\n for label in item[0]:\n tags[label]=1\n\n if len(list(item[0]))==len(list(item[1])) and \"M-描述\" not in item[0]:\n lb=[]\n for l in item[0]:\n if l.endswith(\"关系\") or l.endswith(\"实体\") or l.endswith(\"O\"):\n lb.append(l)\n elif l.endswith(\"属性\"):\n lb.append(l.replace(\"属性\",'关系'))\n else:\n lb.append(\"O\")\n\n one={\"text\":item[1], \"label\":lb}\n data.append(one)\n else:\n # print(\"pass\")\n pass\n if type==\"all\":\n pass\n elif type==\"mini\":\n data=data[:200]\n # print(tags)\n # with open(\"data/tag.txt\",\"w\") as f:\n # f.write(\"\\n\".join(tags.keys()))\n\n f=int(len(data)*0.85)\n tjson_save.save(data=data[:f])\n dev_json_save.save(data=data[f:])\n return tags\n\ndef run(input_files,path):\n # data=_read_data(input_file)\n # print(data)\n tags=None\n for f in input_files:\n print(f)\n tags=build_ner(f,path,tags)\n\n\n\ndef saoke():\n saoke=Tjson(file_path=\"data/SAOKE_DATA.json\")\n i=0\n for line in saoke.load():\n print(\"###\"*20)\n print(line)\n print(line['natural'])\n for logic in line['logic']:\n print(logic)\n print(logic['predicate'])\n print(logic['qualifier'])\n # print(logic['object'])\n for object in logic['object']:\n print(object)\n print(logic['place'])\n print(logic['time'])\n \n print(logic['subject'])\n i=i+1\n if i>10:\n exit()\n\n\n\n\n# 只保存关系和实体标注\n\n#处理标记过的数据\npath=\"/mnt/data/dev/github/数据处理工具/tool_data_processing/data/text/\"\ntfile=tkit.File()\ninput_files=tfile.file_List( path, type='anns')\nsavepath=\"/mnt/data/dev/github/open-entity-relation-extraction关系提取/open-entity-relation-extraction/tdata/ner/\"\nrun(input_files,savepath)","sub_path":"只保存关系和实体标注.py","file_name":"只保存关系和实体标注.py","file_ext":"py","file_size_in_byte":9458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"249798327","text":"import os\nimport re\nimport fnmatch\ndef find_files(directory, pattern):\n\tfor root, dirs, files in os.walk(directory):\n\t\tfor basename in files:\n\t\t\tif fnmatch.fnmatch(basename.lower(), pattern):\n\t\t\t\tfilename = os.path.join(root, basename)\n\t\t\t\tyield filename\n\ndir = '/test/'\nfor filename in find_files(dir, 'makefile'):\n\twith open(filename, 'r') as f:\n\t\ts = f.read()\n\t\tf.close()\n\t\ts = re.sub(\"-Wall|-Werror|-Wextra\", \"\", s)\n\t\ts = re.sub(\"gcc\", \"gcc -w\", s)\n\t\twith open(filename, 'w') as i:\n\t\t\ti.write(s)\n","sub_path":"printftest/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"60875891","text":"from .event import EventType, Signal\nfrom collections import deque\nimport numpy as np\nimport talib\n\nimport statsmodels.api as sm\ndef regress(prc):\n y = np.array(prc)\n y = y[~np.isnan(y)]\n x = range(len(y))\n x = sm.add_constant(x)\n model = sm.OLS(y, x).fit()\n return model\n\nclass RegressionSlope(object):\n\tdef __init__(self, context, l1=10):\n\t\tassert l1 > 24\n\t\tself.context = context\n\t\tself.l1 = l1\n\t\tself.ma_bars = deque(maxlen=l1+2)\n\t\tself.bars = 0\n\t\tself.context.portfolio.slope_list = [0]*(l1+2)\n\n\tdef calculate_signal(self, event):\n\t\tif event.type == EventType.BAR:\n\t\t\tself.ma_bars.append(event.CC)\n\t\t\tself.bars += 1\n\n\t\t\t# has enough bars\n\t\t\tif self.bars > self.l1+2:\n\t\t\t\tmoving_average = (talib.MA(np.array(self.ma_bars), self.l1) - np.mean(self.ma_bars)) / np.std(self.ma_bars)\n\t\t\t\tslope = regress(moving_average[-24:]).params[1]\n\t\t\t\tself.context.portfolio.slope_list.append(slope)\n\n\t\t\t\t# check signal values\n\t\t\t\tsignal = 0\n\t\t\t\tif slope > 0.001:\n\t\t\t\t\tsignal = 1\n\t\t\t\telif slope < -0.001:\n\t\t\t\t\tsignal = -1\n\n\t\t\t\tif self.context.portfolio.position > 0 and slope < 0:\n\t\t\t\t\tsignal = -1\n\t\t\t\telif self.context.portfolio.position < 0 and slope > 0:\n\t\t\t\t\tsignal = 1\n\n\t\t\t\tcurr_signal = Signal(signal, event.CC)\n\t\t\t\tself.context.portfolio_handler.on_signal(curr_signal)\n","sub_path":"framework/regression_slope.py","file_name":"regression_slope.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"116482199","text":"\"\"\"\nimplement a simplified VGG to detect sorghum flowering time\n\"\"\"\nfrom glob import glob\nimport numpy as np\nimport pickle\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import History\nfrom keras.optimizers import Adam\nfrom keras.optimizers import SGD\n\nts = (256, 256)\ndef preprocess(img_dir):\n imgs = []\n all_imgs = glob(img_dir + '/*/*png')\n for i in all_imgs:\n img = load_img(i, target_size = ts)\n img_array = img_to_array(img)\n imgs.append(img_array)\n imgs = np.array(imgs)\n #print(imgs.shape)\n #print('the demension of image array: %s'%(','.join([str(i) for i in imgs.shape]))) \n return imgs\n\ndef train(train_dir, val_dir, Categories, lr, epc, model_name):\n train_imgs = preprocess(train_dir)\n val_imgs = preprocess(val_dir)\n\n train_datagen = ImageDataGenerator(\n rescale = 1./255,\n featurewise_center=True,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2\n )\n train_datagen.fit(train_imgs)\n train_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=ts,\n batch_size=40, \n shuffle=True\n #save_to_dir = '%s_augmented_train_imgs'%model_name,\n #save_prefix = 'aug_train'\n ) \n\n val_datagen = ImageDataGenerator(\n rescale = 1./255,\n featurewise_center=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2\n )\n val_datagen.fit(val_imgs)\n val_generator = val_datagen.flow_from_directory(\n val_dir,\n target_size=ts,\n batch_size=20, \n shuffle=True\n #save_to_dir = '%s_augmented_val_imgs'%model_name,\n #save_prefix = 'aug_val'\n ) \n print('data well prepared')\n model = Sequential([\n Conv2D(64, (3, 3), input_shape=(256, 256, 3), padding='same', activation='relu'),\n Conv2D(64, (3, 3), activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n #Dropout(0.2),\n Conv2D(128, (3, 3), activation='relu', padding='same'),\n Conv2D(128, (3, 3), activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n #Dropout(0.2),\n Conv2D(256, (3, 3), activation='relu', padding='same'),\n Conv2D(256, (3, 3), activation='relu', padding='same'),\n Conv2D(256, (3, 3), activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n #Dropout(0.2),\n Conv2D(512, (3, 3), activation='relu', padding='same'),\n Conv2D(512, (3, 3), activation='relu', padding='same'),\n Conv2D(512, (3, 3), activation='relu', padding='same'),\n MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n #Dropout(0.25),\n #Conv2D(512, (3, 3), activation='relu', padding='same',),\n #Conv2D(512, (3, 3), activation='relu', padding='same',),\n #Conv2D(512, (3, 3), activation='relu', padding='same',),\n #MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),\n #Dropout(0.25),\n Flatten(),\n Dense(500, activation='relu'),\n #Dropout(0.5),\n Dense(int(Categories), activation='softmax')\n ])\n print('structure designed')\n model.summary()\n print('start compiling')\n model.compile(\n loss='categorical_crossentropy',\n optimizer=Adam(lr=float(lr)), \n #optimizer=SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True), \n metrics=['accuracy']\n )\n print('compile done')\n model_history = model.fit_generator(\n train_generator, \n epochs=int(epc), \n validation_data=val_generator\n )\n\n model.save('%s.h5'%model_name)\n print('model has been saved to %s.h5'%model_name)\n\n pickle.dump(model_history.history, open( \"%s_history.p\"%model_name, \"wb\" ) )\n print(\"model history has been saved to a pickle object %s_history.p.\"%model_name)\n\nimport sys\nif len(sys.argv)==7:\n train(*sys.argv[1:])\nelse:\n print('train_dir', 'val_dir', 'categories_num', 'lr', 'epoch', 'model_name')\n","sub_path":"CNN/keras_vgg.py","file_name":"keras_vgg.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"139850659","text":"# encoding: utf-8\n\"\"\"\n菜单\n@author Yuriseus\n@create 2016-12-10 21:24\n\"\"\"\nfrom .base import BaseModel\n\n\nclass Menu(BaseModel):\n def __init__(self):\n self.id = 0\n self.name = ''\n self.url = ''\n self.sort = 0\n self.parent_id = 0\n self.status = 1\n\n","sub_path":"models/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"145182479","text":"import re\nfrom .bag_graph import BagGraph, Bag\n\n\nclass Day07:\n # Started 1:48 later than start.\n def __init__(self, data):\n self.raw_data = data\n self.bag_graph = BagGraph()\n\n def solve_part1(self):\n self.load_input()\n print(self.bag_graph)\n\n target_color = \"shiny gold\"\n\n valid_colors = set()\n for color in self.bag_graph.colors():\n if self.bag_graph.can_contain(color, target_color):\n valid_colors.add(color)\n\n print(f\"Count: {len(valid_colors)}, Valid Colors: {valid_colors}\")\n\n def solve_part2(self):\n self.load_input()\n target_color = \"shiny gold\"\n target_bag = self.bag_graph.get_bag(target_color)\n\n print(f\"{target_color} holds {target_bag.holds(self.bag_graph) - 1} bags.\")\n\n def load_input(self):\n\n for line in self.raw_data:\n\n \"\"\"\n light red bags contain 1 bright white bag, 2 muted yellow bags.\n dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n bright white bags contain 1 shiny gold bag.\n muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\n dark olive bags contain 3 faded blue bags, 4 dotted black bags.\n vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\n faded blue bags contain no other bags.\n dotted black bags contain no other bags.\n \"\"\"\n bag_color_pattern = re.compile(r\"^(\\w+ \\w+) bags contain\")\n no_other_pattern = re.compile(r\"no other bags.$\")\n\n bag_color = bag_color_pattern.match(line)[1]\n bag = Bag(bag_color)\n\n if no_other_pattern.match(line):\n pass\n else:\n containing = re.findall(r\"(\\d+) (\\w+ \\w+)\", line)\n\n for b in containing:\n quantity = b[0]\n color = b[1]\n bag.add_inner_bag(quantity, color)\n\n print(f\"Added {bag}\")\n self.bag_graph.add_bag(bag)\n","sub_path":"day07/day07.py","file_name":"day07.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"613436020","text":"\nimport os\nimport cv2\n\nfrom scipy.ndimage.filters import median_filter\n\n#Size of images\nIMAGE_WIDTH = 1920#395#1920#227\nIMAGE_HEIGHT = 960#264#960#227\n\ndef transform_img_and_denoise(img, img_width=IMAGE_WIDTH, img_height=IMAGE_HEIGHT):\n\n #Histogram Equalization\n img[:, :, 0] = cv2.equalizeHist(img[:, :, 0])\n img[:, :, 1] = cv2.equalizeHist(img[:, :, 1])\n img[:, :, 2] = cv2.equalizeHist(img[:, :, 2])\n\n\n #Image Denoising\n #img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)\n \n #Image Resizing\n #img = cv2.resize(img, (img_width, img_height), interpolation = cv2.INTER_CUBIC)\n\n return img\n\ndef sharpen_image(img, sigma, strength):\n #Image Median filtering \n img_mf = median_filter(img, sigma)\n\n #Laplacial Calculation\n lap = cv2.Laplacian(img_mf, cv2.CV_64F)\n\n #Sharpen the Image\n sharp = img-strength*lap\n\n #Saturate Pixels\n\n sharp[sharp>255] =255\n sharp[sharp<0] = 0\n\n return sharp\n\n\n#parent_dir = \"/home/pakoxtror/Desktop/\"\n#directory = \"pruebaeq\"\n#path = os.path.join(parent_dir, directory)\n#os.mkdir(path)\n\n\"\"\" for file in os.listdir(\"/home/pakoxtror/Desktop/prueba\"):\n filename = os.fsdecode(file)\n if filename.endswith(\".jpg\"):\n direc = \"/home/pakoxtror/Desktop/prueba/\"+ filename\n print(direc)\n img = cv2.imread(direc, cv2.IMREAD_COLOR)\n img = transform_img_and_denoise(img, IMAGE_WIDTH, IMAGE_HEIGHT)\n img = sharpen_image(img, 5, 0.8)\n saveas = \"/home/pakoxtror/Desktop/pruebaeq/\" + filename\n cv2.imwrite(saveas , img) \"\"\"\nimg = cv2.imread(\"elena.jpg\", cv2.IMREAD_COLOR)\nheight, width, channels = img.shape \nprint(img.shape)\nimg1 = transform_img_and_denoise(img, IMAGE_WIDTH, IMAGE_HEIGHT)\ncv2.imwrite(\"elena_1.jpg\" , img1)\nimg2 = sharpen_image(img1, 5, 0.8)\ncv2.imwrite(\"elena_2.jpg\" , img2)\n","sub_path":"data_preparation/preprecess.py","file_name":"preprecess.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"604305521","text":"from django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.contrib.auth.models import User\nfrom jadwal_jaga.models import jadwal\nfrom django.shortcuts import render,redirect, get_object_or_404,get_list_or_404\n\nregister = template.Library()\n@register.filter()\ndef get_name_from_kdjaga(value):\n user = User.objects.all()\n for u in user:\n if u.username == value :\n return u.get_full_name()\n return value\n\n\n\n@register.filter()\ndef koderuang(value,ruang):\n m=[];\n for a in value:\n if ruang == a.ruang:\n m.append(a.kd_jaga)\n else:\n m.append(\" \")\n return ruang\n\n@register.filter()\ndef kodesesi(value,sesi):\n for a in value:\n vsesi = a[-1:]\n if sesi == vsesi:\n return a\n return \"tambah_jadwal\"\n\n\n@register.filter()\ndef cocok(value,bs):\n try:\n name = jadwal.objects.values_list(bs,flat=True).get(kd_jaga=value)\n return name\n except :\n return \"---------\"\n\n\n@register.filter()\ndef ambiljadwal(value):\n try:\n tingkat = jadwal.objects.values_list('tingkat',flat=True).get(kd_jaga=value)\n materi = jadwal.objects.values_list('materi',flat=True).get(kd_jaga=value)\n if tingkat == \"fu\":\n tingkat = \"Fundamental\"\n elif tingkat == \"be\":\n tingkat = \"Beginner\"\n elif tingkat == \"in\":\n tingkat = \"Intermediate\"\n elif tingkat == \"pe\":\n tingkat = \"Pengulangan\"\n\n return (tingkat+\" \"+materi)\n except :\n return \"---------\"\n","sub_path":"jadwal_jaga/templatetags/app_filter.py","file_name":"app_filter.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"124781185","text":"from os.path import join\nfrom myp import MYPReader\nfrom myp import const as myp_const\nfrom typing import List\nfrom ..utils import (\n info_message,\n process_ok,\n process_step,\n success_message,\n hl,\n take_input\n)\nfrom .utils import (\n remove_app,\n remove_app_imports\n)\nfrom ..__main__ import main\n\n@main.command(\"removeapp\")\ndef removeapp_command():\n \"\"\"Remove app in project\"\"\"\n myp:MYPReader = MYPReader()\n prj_name:str = myp.get_data(\"config\").get('PROJECT_NAME', '')\n app_list:List[str] = myp.get_data(\"config\").get('APPS', [])\n processes:List[str] = []\n process_ok(processes)\n\n # Taking app name to remove\n app_name = take_input(\"Enter name of app to remove:\")\n\n # Removing app folder\n if not prj_name :\n raise Exception(f\"You deleted your project name from {myp_const.filename} file. Please add it.\")\n if not app_name in app_list:\n raise Exception(\"Your app name is not in app list\")\n process_step(f\"Removing {hl(join(prj_name, app_name))} folder...\",\n remove_app(join(prj_name, app_name)))\n processes.append(f\"Removed {hl(join(prj_name, app_name))} folder\")\n process_ok(processes)\n\n # Removing app name from myp.json\n myp_config = myp.get_config()\n myp_config['APPS'].remove(app_name)\n myp.set_config(myp_config)\n myp.write()\n\n # Removing app modules from __init__.py\n process_step(f\"Removing imports of {hl(app_name)} from {hl(join(prj_name, '__init__.py'))}...\",\n remove_app_imports(prj_name, app_name))\n processes.append(f\"Removed imports of {hl(app_name)} from {hl(join(prj_name, '__init__.py'))}\")\n process_ok(processes)\n\n # Output success message\n success_message(f\"Successfully removed {hl(app_name)}\")\n info_message(f\"Use {hl('myp start')} to run your application\")\n","sub_path":"flaskmng/removeapp/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"189064705","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\nfrom typing import List\nimport os\nimport csv\nimport warnings\nimport cv2\nimport numpy as np\n\nfrom pycocotools.cocoeval import COCOeval\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport seaborn as sns\n\n\nplt.switch_backend('agg')\nwarnings.filterwarnings(\"ignore\")\nCOLOR_MAP = [\n (0, 255, 255),\n (0, 255, 0),\n (255, 0, 0),\n (0, 0, 255),\n (255, 255, 0),\n (255, 0, 255),\n (0, 128, 128),\n (0, 128, 0),\n (128, 0, 0),\n (0, 0, 128),\n (128, 128, 0),\n (128, 0, 128),\n]\n\n\ndef write_list_to_csv(file_path, data_to_write, append=False):\n print('Saving data into file [{}]...'.format(file_path))\n if append:\n open_mode = 'a'\n else:\n open_mode = 'w'\n with open(file_path, open_mode) as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(data_to_write)\n\n\ndef read_image(image_path):\n image = cv2.imread(image_path)\n if image is None:\n return False, None\n return True, image\n\n\ndef save_image(image_path, image):\n return cv2.imwrite(image_path, image)\n\n\ndef draw_rectangle(image, pt1, pt2, label=None):\n if label is not None:\n map_index = label % len(COLOR_MAP)\n color = COLOR_MAP[map_index]\n else:\n color = COLOR_MAP[0]\n thickness = 5\n cv2.rectangle(image, pt1, pt2, color, thickness)\n\n\ndef draw_text(image, text, org, label=None):\n if label is not None:\n map_index = label % len(COLOR_MAP)\n color = COLOR_MAP[map_index]\n else:\n color = COLOR_MAP[0]\n font_face = cv2.FONT_HERSHEY_SIMPLEX\n font_scale = 0.6\n thickness = 1\n cv2.putText(image, text, org, font_face, font_scale, color, thickness)\n\n\ndef draw_one_box(image, label, box, cat_id, line_thickness=None):\n tl = line_thickness or round(0.002 * (image.shape[0] + image.shape[1]) / 2) + 1\n if cat_id is not None:\n map_index = cat_id % len(COLOR_MAP)\n color = COLOR_MAP[map_index]\n else:\n color = COLOR_MAP[0]\n c1, c2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))\n cv2.rectangle(image, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n\n tf = max(tl - 1, 1)\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf // 2)[0]\n c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n cv2.rectangle(image, c1, c2, color, -1, cv2.LINE_AA)\n cv2.putText(image, label, (c1[0], c1[1] - 2), 0, tl / 6, [255, 255, 255], thickness=tf // 2, lineType=cv2.LINE_AA)\n\n\nclass DetectEval(COCOeval):\n def __init__(self, cocoGt=None, cocoDt=None, iouType=\"bbox\"):\n assert iouType == \"bbox\", \"iouType only supported bbox\"\n\n super().__init__(cocoGt, cocoDt, iouType)\n if not self.cocoGt is None:\n cat_infos = cocoGt.loadCats(cocoGt.getCatIds())\n self.params.labels = {}\n # self.params.labels = [\"\" for i in range(len(self.params.catIds))]\n for cat in cat_infos:\n self.params.labels[cat[\"id\"]] = cat[\"name\"]\n\n # add new\n def catId_summarize(self, catId, iouThr=None, areaRng=\"all\", maxDets=100):\n p = self.params\n aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]\n mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]\n\n s = self.eval[\"recall\"]\n if iouThr is not None:\n iou = np.where(iouThr == p.iouThrs)[0]\n s = s[iou]\n\n if isinstance(catId, int):\n s = s[:, catId, aind, mind]\n else:\n s = s[:, :, aind, mind]\n\n not_empty = len(s[s > -1]) == 0\n if not_empty:\n mean_s = -1\n else:\n mean_s = np.mean(s[s > -1])\n return mean_s\n\n def compute_gt_dt_num(self):\n p = self.params\n catIds_gt_num = {}\n catIds_dt_num = {}\n\n for ids in p.catIds:\n gts_cat_id = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(catIds=[ids]))\n dts_cat_id = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(catIds=[ids]))\n catIds_gt_num[ids] = len(gts_cat_id)\n catIds_dt_num[ids] = len(dts_cat_id)\n\n return catIds_gt_num, catIds_dt_num\n\n def evaluate_ok_ng(self, img_id, catIds, iou_threshold=0.5):\n \"\"\"\n evaluate every if this image is ok、precision_ng、recall_ng\n img_id: int\n cat_ids:list\n iou_threshold:int\n \"\"\"\n p = self.params\n img_id = int(img_id)\n\n # Save the results of precision_ng and recall_ng for each category on a picture\n cat_id_result = {}\n for cat_id in catIds:\n gt = self._gts[img_id, cat_id]\n dt = self._dts[img_id, cat_id]\n ious = self.computeIoU(img_id, cat_id)\n\n # Sort dt in descending order, and only take the first 100\n inds = np.argsort([-d['score'] for d in dt], kind='mergesort')\n dt = [dt[i] for i in inds]\n\n # p.maxDets must be set in ascending order\n if len(dt) > p.maxDets[-1]:\n dt = dt[0:p.maxDets[-1]]\n\n # The first case: gt, dt are both 0: skip\n if not gt and not dt:\n cat_id_result[cat_id] = (False, False)\n continue\n # The second case: gt = 0, dt !=0: precision_ng\n if not gt and dt:\n cat_id_result[cat_id] = (True, False)\n continue\n # The third case: gt != 0, dt = 0: recall_ng\n if gt and not dt:\n cat_id_result[cat_id] = (False, True)\n continue\n # The fourth case: gt and dt are matched in pairs\n gtm = [0] * len(gt)\n dtm = [0] * len(dt)\n\n for dind in range(len(dt)):\n # dt:[a] gt [b] ious = [a*b]\n iou = min([iou_threshold, 1 - 1e-10])\n # m records the position of the gt with the best match\n m = -1\n for gind in range(len(gt)):\n # If gt[gind] already matches, skip it.\n if gtm[gind] > 0:\n continue\n # If the iou(dind, gind) is less than the threshold, traverse\n if ious[dind, gind] < iou:\n continue\n iou = ious[dind, gind]\n m = gind\n if m == -1:\n continue\n dtm[dind] = 1\n gtm[m] = 1\n\n # If gt is all matched, gtm is all 1\n precision_ng = sum(dtm) < len(dtm)\n recall_ng = sum(gtm) < len(gtm)\n cat_id_result[cat_id] = (precision_ng, recall_ng)\n\n # As long as the precision_ng in a class is True, the picture is precision_ng, and recall_ng is the same\n # Subsequent development of NG pictures for each category can be saved\n precision_result = False\n recall_result = False\n for ng in cat_id_result.values():\n precision_ng = ng[0]\n recall_ng = ng[1]\n if precision_ng:\n precision_result = precision_ng\n if recall_ng:\n recall_result = recall_ng\n return precision_result, recall_result\n\n def evaluate_every_class(self):\n \"\"\"\n compute every class's:\n [label, tp_num, gt_num, dt_num, precision, recall]\n \"\"\"\n print(\"Evaluate every class's predision and recall\")\n p = self.params\n cat_ids = p.catIds\n labels = p.labels\n result = []\n catIds_gt_num, catIds_dt_num = self.compute_gt_dt_num()\n sum_gt_num = 0\n sum_dt_num = 0\n for value in catIds_gt_num.values():\n sum_gt_num += value\n for value in catIds_dt_num.values():\n sum_dt_num += value\n sum_tp_num = 0\n\n for i, cat_id in enumerate(cat_ids):\n # Here is hard-coded\n stats = self.catId_summarize(catId=i)\n recall = stats\n gt_num = catIds_gt_num[cat_id]\n tp_num = recall * gt_num\n sum_tp_num += tp_num\n dt_num = catIds_dt_num[cat_id]\n if dt_num <= 0:\n if gt_num == 0:\n precision = -1\n else:\n precision = 0\n else:\n precision = tp_num / dt_num\n label = labels[cat_id]\n class_result = [label, int(round(tp_num)), gt_num, int(round(dt_num)), round(precision, 3),\n round(recall, 3)]\n result.append(class_result)\n all_precision = sum_tp_num / sum_dt_num\n all_recall = sum_tp_num / sum_gt_num\n all_result = [\"all\", int(round(sum_tp_num)), sum_gt_num, int(round(sum_dt_num)), round(all_precision, 3),\n round(all_recall, 3)]\n result.append(all_result)\n\n print(\"Done\")\n return result\n\n def plot_pr_curve(self, eval_result_path):\n\n \"\"\"\n precisions[T, R, K, A, M]\n T: iou thresholds [0.5 : 0.05 : 0.95], idx from 0 to 9\n R: recall thresholds [0 : 0.01 : 1], idx from 0 to 100\n K: category, idx from 0 to ...\n A: area range, (all, small, medium, large), idx from 0 to 3\n M: max dets, (1, 10, 100), idx from 0 to 2\n \"\"\"\n print(\"Plot pr curve about every class\")\n precisions = self.eval[\"precision\"]\n p = self.params\n cat_ids = p.catIds\n labels = p.labels\n\n pr_dir = os.path.join(eval_result_path, \"./pr_curve_image\")\n if not os.path.exists(pr_dir):\n os.mkdir(pr_dir)\n\n for i, cat_id in enumerate(cat_ids):\n pr_array1 = precisions[0, :, i, 0, 2] # iou = 0.5\n x = np.arange(0.0, 1.01, 0.01)\n # plot PR curve\n plt.plot(x, pr_array1, label=\"iou=0.5,\" + labels[cat_id])\n plt.xlabel(\"recall\")\n plt.ylabel(\"precision\")\n plt.xlim(0, 1.0)\n plt.ylim(0, 1.01)\n plt.grid(True)\n plt.legend(loc=\"lower left\")\n plt_path = os.path.join(pr_dir, \"pr_curve_\" + labels[cat_id] + \".png\")\n plt.savefig(plt_path)\n plt.close(1)\n print(\"Done\")\n\n def save_images(self, config, eval_result_path, iou_threshold=0.5):\n \"\"\"\n save ok_images, precision_ng_images, recall_ng_images\n Arguments:\n config: dict, config about parameters\n eval_result_path: str, path to save images\n iou_threshold: int, iou_threshold\n \"\"\"\n print(\"Saving images of ok ng\")\n p = self.params\n img_ids = p.imgIds\n cat_ids = p.catIds if p.useCats else [-1] # list: [0,1,2,3....]\n labels = p.labels\n\n dt = self.cocoDt.getAnnIds()\n dts = self.cocoDt.loadAnns(dt)\n\n for img_id in img_ids:\n img_id = int(img_id)\n img_info = self.cocoGt.loadImgs(img_id)\n\n if config.dataset == \"coco\":\n im_path_dir = os.path.join(config.coco_root, config.val_data_type)\n elif config.dataset == \"voc\":\n im_path_dir = os.path.join(config.voc_root, 'eval', \"JPEGImages\")\n\n assert config.dataset in (\"coco\", \"voc\")\n\n # Return whether the image is precision_ng or recall_ng\n precision_ng, recall_ng = self.evaluate_ok_ng(img_id, cat_ids, iou_threshold)\n # Save to ok_images\n if not precision_ng and not recall_ng:\n # origin image path\n im_path = os.path.join(im_path_dir, img_info[0]['file_name'])\n # output image path\n im_path_out_dir = os.path.join(eval_result_path, 'ok_images')\n if not os.path.exists(im_path_out_dir):\n os.makedirs(im_path_out_dir)\n im_path_out = os.path.join(im_path_out_dir, img_info[0]['file_name'])\n\n success, image = read_image(im_path)\n assert success\n\n for obj in dts:\n _id = obj[\"image_id\"]\n if _id == img_id:\n bbox = obj[\"bbox\"]\n score = obj[\"score\"]\n category_id = obj[\"category_id\"]\n label = labels[category_id]\n\n xmin = int(bbox[0])\n ymin = int(bbox[1])\n width = int(bbox[2])\n height = int(bbox[3])\n xmax = xmin + width\n ymax = ymin + height\n\n label = label + \" \" + str(round(score, 3))\n draw_one_box(image, label, (xmin, ymin, xmax, ymax), category_id)\n save_image(im_path_out, image)\n else:\n # Save to precision_ng_images\n if precision_ng:\n # origin image path\n im_path = os.path.join(im_path_dir, img_info[0]['file_name'])\n assert os.path.exists(im_path), \"{} not exist, please check image directory\".format(im_path)\n # output image path\n im_path_out_dir = os.path.join(eval_result_path, 'precision_ng_images')\n if not os.path.exists(im_path_out_dir):\n os.makedirs(im_path_out_dir)\n im_path_out = os.path.join(im_path_out_dir, img_info[0]['file_name'])\n\n success, image = read_image(im_path)\n assert success\n\n for obj in dts:\n _id = obj[\"image_id\"]\n if _id == img_id:\n bbox = obj[\"bbox\"]\n score = obj[\"score\"]\n category_id = obj[\"category_id\"]\n label = labels[category_id]\n\n xmin = int(bbox[0])\n ymin = int(bbox[1])\n width = int(bbox[2])\n height = int(bbox[3])\n xmax = xmin + width\n ymax = ymin + height\n\n label = label + \" \" + str(round(score, 3))\n draw_one_box(image, label, (xmin, ymin, xmax, ymax), category_id)\n save_image(im_path_out, image)\n\n # Save to recall_ng_images\n if recall_ng:\n # origin image path\n im_path = os.path.join(im_path_dir, img_info[0]['file_name'])\n # output image path\n im_path_out_dir = os.path.join(eval_result_path, 'recall_ng_images')\n if not os.path.exists(im_path_out_dir):\n os.makedirs(im_path_out_dir)\n\n im_path_out = os.path.join(im_path_out_dir, img_info[0]['file_name'])\n success, image = read_image(im_path)\n if not success:\n raise Exception('Failed reading image from [{}]'.format(im_path))\n for obj in dts:\n _id = obj[\"image_id\"]\n if _id == img_id:\n bbox = obj[\"bbox\"]\n score = obj[\"score\"]\n category_id = obj[\"category_id\"]\n label = labels[category_id]\n\n xmin = int(bbox[0])\n ymin = int(bbox[1])\n width = int(bbox[2])\n height = int(bbox[3])\n xmax = xmin + width\n ymax = ymin + height\n\n label = label + \" \" + str(round(score, 3))\n draw_one_box(image, label, (xmin, ymin, xmax, ymax), category_id)\n save_image(im_path_out, image)\n\n print(\"Done\")\n\n def compute_precison_recall_f1(self, min_score=0.1):\n print('Compute precision, recall, f1...')\n if not self.evalImgs:\n print('Please run evaluate() first')\n p = self.params\n catIds = p.catIds if p.useCats == 1 else [-1]\n labels = p.labels\n\n assert len(p.maxDets) == 1\n assert len(p.iouThrs) == 1\n assert len(p.areaRng) == 1\n\n # get inds to evaluate\n k_list = [n for n, k in enumerate(p.catIds)]\n m_list = [m for n, m in enumerate(p.maxDets)]\n a_list: List[int] = [n for n, a in enumerate(p.areaRng)]\n i_list = [n for n, i in enumerate(p.imgIds)]\n I0 = len(p.imgIds)\n A0 = len(p.areaRng)\n\n # cat_pr_dict:\n # {label1:[precision_li, recall_li, f1_li, score_li], label2:[precision_li, recall_li, f1_li, score_li]}\n cat_pr_dict = {}\n cat_pr_dict_origin = {}\n\n for k0 in k_list:\n Nk = k0 * A0 * I0\n # areagRng\n for a0 in a_list:\n Na = a0 * I0\n # maxDet\n for maxDet in m_list:\n E = [self.evalImgs[Nk + Na + i] for i in i_list]\n E = [e for e in E if not e is None]\n if not E:\n continue\n dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E])\n\n # different sorting method generates slightly different results.\n # mergesort is used to be consistent as Matlab implementation.\n inds = np.argsort(-dtScores, kind='mergesort')\n dtScoresSorted = dtScores[inds]\n\n dtm = np.concatenate([e['dtMatches'][:, 0:maxDet] for e in E], axis=1)[:, inds]\n dtIg = np.concatenate([e['dtIgnore'][:, 0:maxDet] for e in E], axis=1)[:, inds]\n gtIg = np.concatenate([e['gtIgnore'] for e in E])\n npig = np.count_nonzero(gtIg == 0)\n if npig == 0:\n continue\n tps = np.logical_and(dtm, np.logical_not(dtIg))\n fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg))\n\n # Ensure that iou has only one value\n assert (tps.shape[0]) == 1\n assert (fps.shape[0]) == 1\n\n tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)\n fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)\n ids = catIds[k0]\n label = labels[ids]\n\n self.calculate_pr_dict(tp_sum, fp_sum, label, npig, dtScoresSorted, cat_pr_dict, cat_pr_dict_origin,\n min_score=min_score)\n print(\"Done\")\n return cat_pr_dict, cat_pr_dict_origin\n\n def calculate_pr_dict(self, tp_sum, fp_sum, label, npig, dtScoresSorted, cat_pr_dict, cat_pr_dict_origin,\n min_score=0.1):\n # iou\n for (tp, fp) in zip(tp_sum, fp_sum):\n tp = np.array(tp)\n fp = np.array(fp)\n rc = tp / npig\n pr = tp / (fp + tp + np.spacing(1))\n\n f1 = np.divide(2 * (rc * pr), pr + rc, out=np.zeros_like(2 * (rc * pr)), where=pr + rc != 0)\n\n conf_thres = [int(i) * 0.01 for i in range(10, 100, 10)]\n dtscores_ascend = dtScoresSorted[::-1]\n inds = np.searchsorted(dtscores_ascend, conf_thres, side='left')\n pr_new = [0.0] * len(conf_thres)\n rc_new = [0.0] * len(conf_thres)\n f1_new = [0.0] * len(conf_thres)\n pr_ascend = pr[::-1]\n rc_ascend = rc[::-1]\n f1_ascend = f1[::-1]\n try:\n for i, ind in enumerate(inds):\n if conf_thres[i] >= min_score:\n pr_new[i] = pr_ascend[ind]\n rc_new[i] = rc_ascend[ind]\n f1_new[i] = f1_ascend[ind]\n else:\n pr_new[i] = 0.0\n rc_new[i] = 0.0\n f1_new[i] = 0.0\n except IndexError:\n pass\n # Ensure that the second, third, and fourth for loops only enter once\n if label not in cat_pr_dict.keys():\n cat_pr_dict_origin[label] = [pr[::-1], rc[::-1], f1[::-1], dtScoresSorted[::-1]]\n cat_pr_dict[label] = [pr_new, rc_new, f1_new, conf_thres]\n else:\n break\n\n def compute_tp_fp_confidence(self):\n print('Compute tp and fp confidences')\n if not self.evalImgs:\n print('Please run evaluate() first')\n p = self.params\n catIds = p.catIds if p.useCats == 1 else [-1]\n labels = p.labels\n\n assert len(p.maxDets) == 1\n assert len(p.iouThrs) == 1\n assert len(p.areaRng) == 1\n\n # get inds to evaluate\n m_list = [m for n, m in enumerate(p.maxDets)]\n k_list = list(range(len(p.catIds)))\n a_list = list(range(len(p.areaRng)))\n i_list = list(range(len(p.imgIds)))\n\n I0 = len(p.imgIds)\n A0 = len(p.areaRng)\n # cat_dict\n correct_conf_dict = {}\n incorrect_conf_dict = {}\n\n for k0 in k_list:\n Nk = k0 * A0 * I0\n # areagRng\n for a0 in a_list:\n Na = a0 * I0\n # maxDet\n for maxDet in m_list:\n E = [self.evalImgs[Nk + Na + i] for i in i_list]\n E = [e for e in E if not e is None]\n if not E:\n continue\n dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E])\n\n inds = np.argsort(-dtScores, kind='mergesort')\n dtScoresSorted = dtScores[inds]\n\n dtm = np.concatenate([e['dtMatches'][:, 0:maxDet] for e in E], axis=1)[:, inds]\n dtIg = np.concatenate([e['dtIgnore'][:, 0:maxDet] for e in E], axis=1)[:, inds]\n gtIg = np.concatenate([e['gtIgnore'] for e in E])\n npig = np.count_nonzero(gtIg == 0)\n if npig == 0:\n continue\n tps = np.logical_and(dtm, np.logical_not(dtIg))\n fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg))\n\n # Ensure that iou has only one value\n assert (tps.shape[0]) == 1\n assert (fps.shape[0]) == 1\n\n tp_inds = np.where(tps)\n fp_inds = np.where(fps)\n\n tp_confidence = dtScoresSorted[tp_inds[1]]\n fp_confidence = dtScoresSorted[fp_inds[1]]\n tp_confidence_li = tp_confidence.tolist()\n fp_confidence_li = fp_confidence.tolist()\n ids = catIds[k0]\n label = labels[ids]\n\n # Ensure that the second and third for loops only enter once\n if label not in correct_conf_dict.keys():\n correct_conf_dict[label] = tp_confidence_li\n else:\n print(\"maxDet:\", maxDet, \" \", \"areagRng:\", p.areagRng)\n break\n\n if label not in incorrect_conf_dict.keys():\n incorrect_conf_dict[label] = fp_confidence_li\n else:\n print(\"maxDet:\", maxDet, \" \", \"areagRng:\", p.areagRng)\n break\n print(\"Done\")\n return correct_conf_dict, incorrect_conf_dict\n\n def write_best_confidence_threshold(self, cat_pr_dict, cat_pr_dict_origin, eval_result_path):\n \"\"\"\n write best confidence threshold\n \"\"\"\n print(\"Write best confidence threshold to csv\")\n result_csv = os.path.join(eval_result_path, \"best_threshold.csv\")\n result = [\"cat_name\", \"best_f1\", \"best_precision\", \"best_recall\", \"best_score\"]\n write_list_to_csv(result_csv, result, append=False)\n return_result = []\n for cat_name, cat_info in cat_pr_dict.items():\n f1_li = cat_info[2]\n score_li = cat_info[3]\n max_f1 = [f1 for f1 in f1_li if abs(f1 - max(f1_li)) <= 0.001]\n thre_ = [0.003] + [int(i) * 0.001 for i in range(10, 100, 10)] + [0.099]\n # Find the best confidence threshold for 10 levels of confidence thresholds\n if len(max_f1) == 1:\n # max_f1 is on the far right\n if f1_li.index(max_f1) == len(f1_li) - 1:\n index = f1_li.index(max_f1) - 1\n # max_f1 is in the middle\n elif f1_li.index(max_f1) != len(f1_li) - 1 and f1_li.index(max_f1) != 0:\n index_a = f1_li.index(max_f1) - 1\n index_b = f1_li.index(max_f1) + 1\n if f1_li[index_a] >= f1_li[index_b]:\n index = index_a\n else:\n index = f1_li.index(max_f1)\n # max_f1 is on the far left\n elif f1_li.index(max_f1) == 0:\n index = f1_li.index(max_f1)\n\n best_thre = score_li[index]\n # thre_ = [0.003] + [int(i) * 0.001 for i in range(10, 100, 10)] + [0.099]\n second_thre = [best_thre + i for i in thre_]\n\n elif len(max_f1) > 1:\n thre_pre = [index for (index, value) in enumerate(f1_li) if abs(value - max(f1_li)) <= 0.001]\n best_thre = score_li[thre_pre[int((len(thre_pre) - 1) / 2)]]\n # thre_ = [0.003] + [int(i) * 0.001 for i in range(10, 100, 10)] + [0.099]\n second_thre = [best_thre + i for i in thre_]\n\n # Reduce the step unit to find the second confidence threshold\n cat_info_origin = cat_pr_dict_origin[cat_name]\n dtscores_ascend = cat_info_origin[3]\n inds = np.searchsorted(dtscores_ascend, second_thre, side='left')\n\n pr_second = [0] * len(second_thre)\n rc_second = [0] * len(second_thre)\n f1_second = [0] * len(second_thre)\n\n try:\n for i, ind in enumerate(inds):\n if ind >= len(cat_info_origin[0]):\n ind = len(cat_info_origin[0]) - 1\n pr_second[i] = cat_info_origin[0][ind]\n rc_second[i] = cat_info_origin[1][ind]\n f1_second[i] = cat_info_origin[2][ind]\n except IndexError:\n pass\n\n best_f1 = max(f1_second)\n best_index = f1_second.index(best_f1)\n best_precision = pr_second[best_index]\n best_recall = rc_second[best_index]\n best_score = second_thre[best_index]\n result = [cat_name, best_f1, best_precision, best_recall, best_score]\n return_result.append(result)\n write_list_to_csv(result_csv, result, append=True)\n return return_result\n\n def plot_mc_curve(self, cat_pr_dict, eval_result_path):\n \"\"\"\n plot matrix-confidence curve\n cat_pr_dict:{\"label_name\":[precision, recall, f1, score]}\n \"\"\"\n print('Plot mc curve')\n savefig_path = os.path.join(eval_result_path, 'pr_cofidence_fig')\n if not os.path.exists(savefig_path):\n os.mkdir(savefig_path)\n\n xlabel = \"Confidence\"\n ylabel = \"Metric\"\n for cat_name, cat_info in cat_pr_dict.items():\n precision = [round(p, 3) for p in cat_info[0]]\n recall = [round(r, 3) for r in cat_info[1]]\n f1 = [round(f, 3) for f in cat_info[2]]\n score = [round(s, 3) for s in cat_info[3]]\n plt.figure(figsize=(9, 9))\n gs = gridspec.GridSpec(4, 1)\n\n plt.subplot(gs[:3, 0])\n # 1.precision-confidence\n plt.plot(score, precision, linewidth=2, color=\"deepskyblue\", label=\"precision\")\n\n # 2.recall-confidence\n plt.plot(score, recall, linewidth=2, color=\"limegreen\", label=\"recall\")\n\n # 3.f1-confidence\n plt.plot(score, f1, linewidth=2, color=\"tomato\", label=\"f1_score\")\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(cat_name, fontsize=15)\n\n plt.xlim(0, 1)\n plt.xticks((np.arange(0, 1, 0.1)))\n plt.ylim(0, 1.10)\n plt.legend(loc=\"lower left\")\n\n row_name = [\"conf_threshold\", \"precision\", \"recall\", \"f1\"]\n plt.grid(True)\n plt.subplot(gs[3, 0])\n plt.axis('off')\n\n colors = [\"white\", \"deepskyblue\", \"limegreen\", \"tomato\"]\n plt.table(cellText=[score, precision, recall, f1], rowLabels=row_name, loc='center', cellLoc='center',\n rowLoc='center', rowColours=colors)\n\n plt.subplots_adjust(left=0.2, bottom=0.2)\n plt.savefig(os.path.join(savefig_path, cat_name) + '.png', dpi=250)\n print(\"Done\")\n\n def plot_hist_curve(self, input_data, eval_result_path):\n correct_conf_dict, incorrect_conf_dict = input_data[0], input_data[1]\n savefig_path = os.path.join(eval_result_path, 'hist_curve_fig')\n if not os.path.exists(savefig_path):\n os.mkdir(savefig_path)\n for l in correct_conf_dict.keys():\n plt.figure(figsize=(7, 7))\n if l in incorrect_conf_dict.keys() and \\\n len(correct_conf_dict[l]) > 1 and \\\n len(incorrect_conf_dict[l]) > 1:\n gs = gridspec.GridSpec(4, 1)\n plt.subplot(gs[:3, 0])\n correct_conf_dict[l].sort()\n correct_conf_dict[l].reverse()\n col_name_correct = ['number', 'mean', 'max', 'min', 'min99%', 'min99.9%']\n col_val_correct = [len(correct_conf_dict[l]),\n ('%.2f' % np.mean(correct_conf_dict[l])),\n ('%.2f' % max(correct_conf_dict[l])), ('%.2f' % min(correct_conf_dict[l])),\n ('%.2f' % correct_conf_dict[l][int(len(correct_conf_dict[l]) * 0.99) - 1]),\n ('%.2f' % correct_conf_dict[l][int(len(correct_conf_dict[l]) * 0.999) - 1])]\n sns.set_palette('hls')\n sns.distplot(correct_conf_dict[l], bins=50, kde_kws={'color': 'b', 'lw': 3},\n hist_kws={'color': 'b', 'alpha': 0.3})\n plt.xlim((0, 1))\n plt.xlabel(l)\n plt.ylabel(\"numbers\")\n ax1 = plt.twinx()\n incorrect_conf_dict[l].sort()\n incorrect_conf_dict[l].reverse()\n col_val_incorrect = [len(incorrect_conf_dict[l]),\n ('%.2f' % np.mean(incorrect_conf_dict[l])),\n ('%.2f' % max(incorrect_conf_dict[l])), ('%.2f' % min(incorrect_conf_dict[l])),\n ('%.2f' % incorrect_conf_dict[l][int(len(incorrect_conf_dict[l]) * 0.99) - 1]),\n ('%.2f' % incorrect_conf_dict[l][int(len(incorrect_conf_dict[l]) * 0.999) - 1])]\n sns.distplot(incorrect_conf_dict[l], bins=50, kde_kws={'color': 'r', 'lw': 3},\n hist_kws={'color': 'r', 'alpha': 0.3}, ax=ax1)\n plt.grid(True)\n plt.subplot(gs[3, 0])\n plt.axis('off')\n row_name = ['', 'correct', 'incorrect']\n table = plt.table(cellText=[col_name_correct, col_val_correct, col_val_incorrect], rowLabels=row_name,\n loc='center', cellLoc='center', rowLoc='center')\n table.auto_set_font_size(False)\n table.set_fontsize(10)\n table.scale(1, 1.5)\n plt.savefig(os.path.join(savefig_path, l) + '.jpg')\n elif len(correct_conf_dict[l]) > 1:\n gs = gridspec.GridSpec(4, 1)\n plt.subplot(gs[:3, 0])\n correct_conf_dict[l].sort()\n correct_conf_dict[l].reverse()\n col_name_correct = ['number', 'mean', 'max', 'min', 'min99%', 'min99.9%']\n col_val_correct = [len(correct_conf_dict[l]),\n ('%.4f' % np.mean(correct_conf_dict[l])),\n ('%.4f' % max(correct_conf_dict[l])), ('%.2f' % min(correct_conf_dict[l])),\n ('%.2f' % correct_conf_dict[l][int(len(correct_conf_dict[l]) * 0.99) - 1]),\n ('%.2f' % correct_conf_dict[l][int(len(correct_conf_dict[l]) * 0.999) - 1])]\n sns.set_palette('hls')\n sns.distplot(correct_conf_dict[l], bins=50, kde_kws={'color': 'b', 'lw': 3},\n hist_kws={'color': 'b', 'alpha': 0.3})\n plt.xlim((0, 1))\n plt.xlabel(l)\n plt.ylabel(\"numbers\")\n plt.grid(True)\n plt.subplot(gs[3, 0])\n plt.axis('off')\n row_name = ['', 'correct']\n table = plt.table(cellText=[col_name_correct, col_val_correct], rowLabels=row_name,\n loc='center', cellLoc='center', rowLoc='center')\n table.auto_set_font_size(False)\n table.set_fontsize(10)\n table.scale(1, 1.5)\n plt.savefig(os.path.join(savefig_path, l) + '.jpg')\n elif l in incorrect_conf_dict.keys() and len(incorrect_conf_dict[l]) > 1:\n gs = gridspec.GridSpec(4, 1)\n plt.subplot(gs[:3, 0])\n incorrect_conf_dict[l].sort()\n incorrect_conf_dict[l].reverse()\n col_name_correct = ['number', 'mean', 'max', 'min', 'min99%', 'min99.9%']\n col_val_correct = [len(incorrect_conf_dict[l]),\n ('%.4f' % np.mean(incorrect_conf_dict[l])),\n ('%.4f' % max(incorrect_conf_dict[l])), ('%.2f' % min(incorrect_conf_dict[l])),\n ('%.2f' % incorrect_conf_dict[l][int(len(incorrect_conf_dict[l]) * 0.99) - 1]),\n ('%.2f' % incorrect_conf_dict[l][int(len(incorrect_conf_dict[l]) * 0.999) - 1])]\n sns.set_palette('hls')\n sns.distplot(incorrect_conf_dict[l], bins=50, kde_kws={'color': 'b', 'lw': 3},\n hist_kws={'color': 'b', 'alpha': 0.3})\n plt.xlim((0, 1))\n plt.xlabel(l)\n plt.grid(True)\n plt.subplot(gs[3, 0])\n plt.axis('off')\n row_name = ['', 'incorrect']\n table = plt.table(cellText=[col_name_correct, col_val_correct], rowLabels=row_name,\n loc='center', cellLoc='center', rowLoc='center')\n table.auto_set_font_size(False)\n table.set_fontsize(10)\n table.scale(1, 1.5)\n plt.savefig(os.path.join(savefig_path, l) + '.jpg')\n\n\nif __name__ == \"__main__\":\n cocoeval = COCOeval_()\n","sub_path":"official/cv/FasterRCNN/src/detecteval.py","file_name":"detecteval.py","file_ext":"py","file_size_in_byte":35816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"93252925","text":"#!/usr/bin/env python3\n\nimport logging\nimport time\n\nimport RPi.GPIO as GPIO\n\n\ndef CleanupTriggers(now, triggers):\n print (\"\")\n for t in triggers:\n delta = now - t[0]\n if delta < 0.05: continue\n print (delta, t[1])\n\nclass RotaryDial(object):\n\n def __init__(self, pin_lifted, pin_trigger, cb_dialed):\n self._pin_lifted = pin_lifted\n self._pin_trigger = pin_trigger\n self._cb_dialed = cb_dialed\n self._idle = True\n GPIO.setup(pin_lifted, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(pin_trigger, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n # do not change these lightly - these were carefully tweaked\n GPIO.add_event_detect(pin_lifted, GPIO.BOTH, callback=self._lifted, bouncetime=25)\n GPIO.add_event_detect(pin_trigger, GPIO.RISING, callback=self._trigger, bouncetime=10)\n self._triggers = []\n \n def _lifted(self, pin):\n now = time.time()\n idle = GPIO.input(pin)\n if idle == self._idle:\n return\n self._idle = idle\n logging.info(\"idle: %d\", idle)\n # we just became idle\n if self._idle:\n self._cb_dialed(len(self._triggers))\n else:\n self._cb_dialed(0)\n self._triggers = []\n\n\n def _trigger(self, pin):\n ts = time.time()\n if not self._idle:\n v = GPIO.input(pin)\n if v:\n self._triggers.append((ts, v))\n \nif __name__ == \"__main__\":\n\n logging.basicConfig(level=logging.INFO)\n GPIO.setmode(GPIO.BCM)\n def dialed(n):\n print (\"dialed\", n)\n \n def main():\n rot = RotaryDial(15, 14, dialed)\n time.sleep(100)\n\n main()\n","sub_path":"Lib/rotary_dial.py","file_name":"rotary_dial.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"573098942","text":"import requests\nfrom requests.exceptions import ConnectTimeout\nimport json\n\n\n\nclass Translate():\n headers = {'User-Agent': 'Mozilla/5.0(Macintosh;U;IntelMacOSX10_6_8;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50'}\n def __init__(self, word):\n self.word = word #初始化单词\n\n \n def translate(self): #用于发送请求,获取数据\n\n '''\n 具体思路:\n 先去有道找到API接口,传入POST请求的参数,返回JSON数据,利用JSON库从中提取出翻译内容\n \n '''\n try:\n url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'\n key = {\n 'type':'AUTO',\n 'i':self.word, #需要翻译的单词或者句子\n 'doctype':'json',\n 'version':'2.1',\n 'keyfrom':'fanyi.web',\n 'ue':'UTF-8',\n 'action':'FY_BY_CLICKBUTTON',\n 'typoResult':'true'\n } \n response = requests.post(url=url, data=key, headers=self.headers) #POST请求\n if response.status_code == 200: \n self.get_word(response.text)\n else:\n print(\"请求失败,请重试\")\n except ConnectTimeout as e:\n print('error: 请求超时')\n\n except Exception as e:\n print(\"Failure: \", str(e))\n\n def get_word(self, data): #解析JSON数据\n if data:\n data = json.loads(data)\n if data:\n result = data.get('translateResult')\n src = result[0][0].get('src')\n tgt = result[0][0].get('tgt')\n print(\"翻译的单词或者句子为:\", src)\n print(\"Translation results for:\", tgt)\n print(\"Exit, please input n\")\n else:\n print(\"返回的不是json数据格式的数据\")\n \n else:\n pass\n\n def main(self):\n self.translate()\n\n\nif __name__ == \"__main__\":\n while True:\n word = input(\"Please enter the need to translate words or sentences:\")\n word = word.lower()\n if word != 'n':\n t = Translate(word)\n t.main()\n else:\n break\n","sub_path":"fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"3141016","text":"import subprocess\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\n\r\n\r\nroot = Tk()\r\nfilename = filedialog.askopenfilename(initialdir = \"/\",title = \"Select file\",filetypes = ((\"json files\",\"*.json\"),(\"all files\",\"*.*\")))\r\nroot.destroy()\r\nprint(filename)\r\n\r\nproc = subprocess.Popen('curl ' + 'localhost:8080 ' + '-d ' + filename, stdout=subprocess.PIPE, shell=True)\r\n\r\n(out,err) = proc.communicate()\r\nprint('\\n', out)\r\nprint('\\n press q to quit')\r\nkey=\"something\"\r\nwhile key != \"q\":\r\n key=str(input())\r\n","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"606585594","text":"# -*- coding: utf-8 -*\n\"\"\"\n ┏┓ ┏┓\n ┏━┛┻━━━━━━━┛┻━┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┗┳ ┗━┓\n ┃ ┣┓\n ┃ ┏┛\n ┗┓┓┏━━━━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n God Bless,Never Bug\n\"\"\"\nimport sys\nfrom getopt import getopt\n\nfrom mysql_operator.backup_operator import BackupOperator\nfrom mysql_operator.cleanup_operator import CleanupOperator\n\n\nclass CliOperator:\n \"\"\"\n How To Use:\n mysql-operator -b [backup database name]\n mysql-operator -d [dropped database name]\n mysql-operator -r [restored database name]\n \"\"\"\n\n @staticmethod\n def _backup(db_name):\n backup_operator = BackupOperator()\n backup_operator.backup(dbs=[db_name])\n\n @staticmethod\n def _restore(filename):\n backup_operator = BackupOperator()\n backup_operator.restore(filename=filename)\n\n @staticmethod\n def _cleanup(db_name):\n cleanup_operator = CleanupOperator()\n cleanup_operator.drop(db_name=db_name)\n\n @classmethod\n def main(cls):\n opts, args = getopt(sys.argv[1:], 'hb:d:r:', ['help=', 'backup=', 'drop=', 'restore'])\n opts_dict = dict(opts)\n if len(opts_dict) > 2 or '-h' in opts_dict:\n sys.exit(cls.__doc__)\n if '-b' in opts_dict:\n cls._backup(db_name=opts_dict['-b'])\n if '-r' in opts_dict:\n cls._restore(filename=opts_dict['-r'])\n if '-d' in opts_dict:\n cls._cleanup(db_name=opts_dict['-d'])\n\n\nif __name__ == '__main__':\n CliOperator.main()\n","sub_path":"mysql_operator/command_line.py","file_name":"command_line.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"234485627","text":"from django.views.generic import DetailView, CreateView, UpdateView, TemplateView\r\nfrom .forms import BusinessPlanForm\r\nfrom .models import BusinessPlan\r\nfrom .utils import try_get_context\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\nimport os\r\nfrom django.shortcuts import get_object_or_404\r\nfrom django.conf import settings\r\nfrom django.http import HttpResponse, Http404\r\nfrom profiles.models import SMEProfile\r\n\r\nclass BusinessPlanDetailView(DetailView):\r\n\r\n def get_object(self):\r\n slug = self.kwargs.get(\"slug\")\r\n if slug is None:\r\n raise Http404\r\n return get_object_or_404(BusinessPlan, slug__iexact=slug)\r\n\r\n def get_context_data(self, *args, **kwargs):\r\n context = super(BusinessPlanDetailView, self).get_context_data(*args, **kwargs)\r\n slug = self.kwargs.get(\"slug\")\r\n if slug:\r\n user = BusinessPlan.objects.get(slug=slug).get_user()\r\n else:\r\n user = self.request.user\r\n full_context = try_get_context(context, user)\r\n return full_context\r\n\r\nclass BusinessPlanCreateView(LoginRequiredMixin, CreateView):\r\n template_name = 'forms/bp_create_form.html'\r\n form_class = BusinessPlanForm\r\n\r\n def get_queryset(self):\r\n return BusinessPlan.objects.filter(user=self.request.user)\r\n\r\n def form_valid(self, form):\r\n obj = form.save(commit=False)\r\n obj.user = self.request.user\r\n return super(BusinessPlanCreateView, self).form_valid(form)\r\n\r\n def get_context_data(self, *args, **kwargs):\r\n context = super(BusinessPlanCreateView, self).get_context_data(*args, **kwargs)\r\n slug = self.kwargs.get(\"slug\")\r\n if slug:\r\n user = BusinessPlan.objects.get(slug=slug).get_user()\r\n else:\r\n user = self.request.user\r\n full_context = try_get_context(context, user)\r\n return full_context\r\n\r\nclass BusinessPlanUpdateView(LoginRequiredMixin, UpdateView):\r\n template_name = 'forms/bp_update_form.html'\r\n form_class = BusinessPlanForm\r\n\r\n def get_queryset(self):\r\n return BusinessPlan.objects.filter(user=self.request.user)\r\n\r\n def get_context_data(self, *args, **kwargs):\r\n context = super(BusinessPlanUpdateView, self).get_context_data(*args, **kwargs)\r\n slug = self.kwargs.get(\"slug\")\r\n if slug:\r\n user = BusinessPlan.objects.get(slug=slug).get_user()\r\n else:\r\n user = self.request.user\r\n full_context = try_get_context(context, user)\r\n return full_context\r\n\r\nclass InfoView(LoginRequiredMixin, TemplateView):\r\n template_name = 'info_view.html'\r\n\r\n def get_context_data(self, *args, **kwargs):\r\n context = super(InfoView, self).get_context_data(*args, **kwargs)\r\n slug = self.kwargs.get(\"slug\")\r\n if slug:\r\n user = SMEProfile.objects.get(slug=slug).get_user()\r\n else:\r\n user = self.request.user\r\n full_context = try_get_context(context, user)\r\n return full_context\r\n\r\ndef download(request, path):\r\n file_path = os.path.join(settings.MEDIA_ROOT, path)\r\n if os.path.exists(file_path):\r\n with open(file_path, 'rb') as fh:\r\n response = HttpResponse(fh.read(), content_type=\"application/vnd.ms-excel\")\r\n response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)\r\n return response\r\n raise Http404","sub_path":"businessplan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"218415980","text":"import logging\n\nfrom pylons import request, response, session, tmpl_context as c\nfrom pylons.controllers.util import redirect_to\nfrom pylons.decorators import validate\nfrom pylons.decorators.rest import restrict\nfrom sqlalchemy import delete\n\nfrom rentfox.lib.base import BaseController, render\nfrom rentfox import model\nimport rentfox.model.meta as meta\nimport rentfox.lib.helpers as h\nfrom rentfox.lib import valid\n\nimport re\nimport json\nimport string\n\nlog = logging.getLogger(__name__)\n\nclass UnitController(BaseController):\n @h.authorize(h.is_manager)\n @h.authenticate\n def __before__(self):\n c.menuSubmenu = 1\n c.menuProperty = 'on'\n c.submenuProperty = 'on'\n \n def view(self, id):\n c.unit = model.Unit.get_unit(id)\n c.property = model.Property.get_property( c.unit.propertyid )\n c.property.photo = c.property.thumbid and model.Photo.path(c.property.thumbid) or ''\n c.floorplan = model.Floorplan.get(c.unit.floorplanid)\n if not c.floorplan:\n redirect_to(controller='property', action='setup', id=c.unit.propertyid, unitId=c.unit.id)\n c.floorplan.photo = c.floorplan.thumbid and model.Photo.path( c.floorplan.thumbid ) or ''\n c.curPropId = c.property.id\n c.curPropName = c.property.name\n c.page_title = c.curPropName + ' #' + c.unit.label\n c.foxAlert = False\n return render('/unit_view.html')\n \n def create(self):\n propertyId = request.POST['propertyId']\n input = request.POST['units']\n input = input.strip(' ')\n \n if input.startswith(('x ', 'X ')):\n errorslist = self.deleteValidate()\n \n if errorslist:\n unitJSON = {\n 'errors': errorslist\n }\n return json.dumps(unitJSON)\n \n input = input.strip(' ')\n input = input.lstrip('x')\n input = input.lstrip('X')\n input = input.replace(' ', '')\n model.Unit.delete_units(input, propertyId)\n else:\n errorslist = self.addValidate()\n \n if errorslist:\n unitJSON = {\n 'errors': errorslist\n }\n return json.dumps(unitJSON)\n \n input = input.replace(' ', '')\n model.Unit.add_units(input, propertyId)\n \n redirect_to(controller='property', action='json', id=propertyId)\n\n\n def updateDescription(self, unitid=None, desc=None):\n model.Unit.update_description(unitid, desc)\n redirect_to(controller='unit', action='json', id=unitid)\n \n def rename(self):\n unitid = request.POST['unitId']\n newlabel = request.POST['unitLabel']\n currentlabel = request.POST['currentLabel']\n propertyId = request.POST['propertyId']\n \n if newlabel == currentlabel:\n redirect_to(controller='property', action='json', id=propertyId)\n \n if model.Unit.unit_exist(newlabel, propertyId):\n errorslist = []\n errorslist.append({'selector':'#unitLabelInput', \"message\":\"This unit already exists\"})\n \n unitJSON = {\n 'errors': errorslist\n }\n return json.dumps(unitJSON)\n else:\n model.Unit.rename(newlabel, unitid)\n \n redirect_to(controller='property', action='json', id=propertyId)\n \n def delete(self):\n unitid = request.POST['unitId']\n propertyId = request.POST['propertyId']\n \n if not unitid:\n errorslist = []\n errorslist.append({'selector':'#deleteUnitLink', \"message\":\"Trying to delete an unit that does not exist\"})\n \n unitJSON = {\n 'errors': errorslist\n }\n return json.dumps(unitJSON)\n \n model.Unit.delete(unitid)\n \n redirect_to(controller='property', action='json', id=propertyId)\n \n def addValidate(self):\n propertyId = request.POST['propertyId']\n units = request.POST['units'].replace(' ', '')\n \n errorslist = []\n \n # Check for anything other than alphanumeric, '-' appears more than once,\n # '-' and ',' appear together, start or end with ',' or '-', or no input\n if not re.match('^[a-zA-Z0-9-,]+$', units) \\\n or re.search('.*[-].*[-].*', units) \\\n or re.search('(?=[-])(?=[,]).*', units) \\\n or units[0] in '-,' or units[-1] in '-,' \\\n or not units:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Please enter valid units with only numbers and letters.\"})\n return errorslist\n \n \n if '-' in units:\n unitRange = units.split('-')\n start = unitRange[0]\n end = unitRange[1]\n total = int(end) - int(start)\n # Special case: Allow for labels such as 12-B or C-2 to be added.\n if (start.isdigit() and end.isalpha())\\\n or (end.isdigit() and start.isalpha()):\n return errorslist\n elif len(start) > 6 or len(end) > 6:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Max length of unit label is 6\"})\n elif re.search('(?=[a-zA-Z]).+', units):\n errorslist.append({'selector':'#unitsInput', \"message\":'Only numbers can be used in the range, i.e. \"100-110\" and not \"100a-110c\"'})\n elif int(end) < int(start):\n errorslist.append({'selector':'#unitsInput', \"message\":\"First number cannot be greater than the second number\"})\n elif total > 300:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Too many units are being added at once. The max is 300 units.\"})\n else:\n record = model.Unit.get_num_units(request.environ.get('COMPANY_ID'))\n unitCount = record[0]\n maxUnits = record[1]\n if total + unitCount > maxUnits:\n errorslist.append({\"message\":\"You are adding more units than the max allowed for your account (\"+str(maxUnits)+\"). If you would like to add \\\n more, please contact us at support@rentfox.net so that we can better accommodate you.\"}) \n elif ',' in units:\n unitList = units.split(',')\n if any([len(unit) > 6 for unit in unitList]):\n errorslist.append({'selector':'#unitsInput', \"message\":\"Max length of unit label is 6\"})\n else:\n total = len(unitList)\n record = model.Unit.get_num_units(request.environ.get('COMPANY_ID'))\n unitCount = record[0]\n maxUnits = record[1]\n if total + unitCount > maxUnits:\n errorslist.append({\"message\":\"You are adding more units than the max allowed for your account (\"+str(maxUnits)+\"). If you would like to add \\\n more, please contact us at support@rentfox.net so that we can better accommodate you.\"})\n \n else:\n if len(units) > 6:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Max length of unit label is 6\"})\n elif units in model.Unit.get_units_list(propertyId):\n errorslist.append({'selector':'#unitsInput', \"message\":\"Unit already exists.\"})\n else:\n record = model.Unit.get_num_units(request.environ.get('COMPANY_ID'))\n unitCount = record[0]\n maxUnits = record[1]\n if unitCount >= maxUnits:\n errorslist.append({\"message\":\"You are adding more units than the max allowed for your account (\"+str(maxUnits)+\"). If you would like to add \\\n more, please contact us at support@rentfox.net so that we can better accommodate you.\"})\n \n return errorslist\n \n def photos(self):\n return json.dumps(model.Unitphoto.getByUnitId( request.GET['unitid']))\n \n def uploadPhoto(self):\n unitid = request.POST['unitid']\n photosInUnit = model.Unitphoto.countPhotosInUnit(unitid)\n if photosInUnit > 24:\n return json.dumps({'errors':[{'selector':'', \"message\":\"Sorry, Rentfox only allows 25 photos per unit.\"}]})\n \n photo = model.Unitphoto.create(unitid)\n if photo:\n return json.dumps(photo)\n else:\n return json.dumps({'errors':[{'selector':'', \"message\":\"Please provide a JPEG, GIF, or PNG image.\"}]})\n \n def removePhoto(self):\n photo = model.Unitphoto.remove(request.POST['photoid'])\n return json.dumps({'success':1})\n \n def deleteValidate(self):\n propertyId = request.POST['propertyId']\n units = request.POST['units']\n units = units.strip(' ')\n units = units.lstrip('x').lstrip('X')\n units = units.replace(' ', '')\n \n errorslist = []\n \n # Check for anything other than alpha-numbers, '-' appears more than once,\n # '-' and ',' appear together, start or end with ',' or '-', or no input\n if not re.match('^[a-zA-Z0-9-,]+$', units) \\\n or re.search('.*[-].*[-].*', units) \\\n or re.search('(?=[-])(?=[,]).*', units) \\\n or units[0] in '-,' or units[-1] in '-,' \\\n or not units:\n errorslist.append({'selector':'#unitsInput', \"message\":'Please enter valid units to delete, i.e. \"x 5\", \"x 5, 15, 25\" or \"x 101-150\".'})\n return errorslist\n \n if '-' in units:\n unitRange = units.split('-')\n start = unitRange[0]\n end = unitRange[1]\n \n # Special case: Allow for labels such as 12-B or C-2 to be deleted.\n if (start.isdigit() and end.isalpha())\\\n or (end.isdigit() and start.isalpha()):\n return errorslist\n \n if re.search('(?=[a-zA-Z]).+', units):\n errorslist.append({'selector':'#unitsInput', \"message\":'Only numbers can be used in the range, i.e. \" x 100-130\" and not \" x 100a-130c\"'})\n elif int(end) < int(start):\n errorslist.append({'selector':'#unitsInput', \"message\":\"First number cannot be greater than the second number\"})\n elif ',' in units:\n unitList = units.split(',')\n existingUnits = model.Unit.get_units_list(propertyId)\n for unit in unitList:\n if unit in existingUnits:\n break\n else:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Trying to delete units that do not exist\"})\n else:\n existingUnits = model.Unit.get_units_list(propertyId)\n if units not in existingUnits:\n errorslist.append({'selector':'#unitsInput', \"message\":\"Trying to delete an unit that does not exist\"})\n \n return errorslist\n\n\n def json(self, id=None):\n unit = model.Unit.get_unit(id)\n floorplanId = unit.floorplanid\n propertyId = unit.propertyid\n \n property = model.Property.get_property(propertyId)\n leases = model.Lease.get_all_from_unit(unit.id)\n\n floorplanInfo = 0\n \n if floorplanId:\n floorplan = model.Floorplan.get(floorplanId)\n \n floorplanInfo = {\n 'id': floorplan.id,\n 'label': floorplan.label,\n 'beds': floorplan.beds,\n 'baths': floorplan.baths,\n 'sqft': floorplan.sqft\n }\n \n propertyInfo = {\n 'id': property.id,\n 'name': property.name\n }\n \n lease = ''\n if leases:\n \tlease = model.Lease.get_current(leases)\n \n \n\n if lease:\n tenants = model.Tenant_lease.getTenantsByLeaseId( lease.id )\n outdate = lease.outdate and lease.outdate.strftime(\"%B %d, %Y\") or 'No date set'\n enddate = lease.enddate and lease.enddate.strftime(\"%B %d, %Y\") or 'No date set'\n editup = lease.enddate and lease.enddate.strftime(\"%m/%d/%Y\") or ''\n leaseInfo = {\n 'id': lease.id,\n 'start': lease.startdate.strftime(\"%B %d, %Y\"),\n 'editStart': lease.startdate.strftime(\"%m/%d/%Y\"),\n 'editUp': editup,\n 'up': enddate,\n 'out': outdate,\n 'deposit': lease.deposit,\n 'depositPaid': lease.depositpaid,\n 'rent': lease.rent,\n 'due': lease.due,\n 'lateCharge': lease.latecharge,\n 'interval': lease.interval,\n 'gracePeriod': lease.graceperiod,\n 'type': 'current',\n 'tenants': tenants,\n 'status': model.Lease.status(lease.startdate, lease.enddate, lease.outdate)\n }\n else:\n leaseInfo = 0\n \n \n tenantsInfo = []\n if lease:\n allTenants = model.Tenant_lease.get_tenants_from_lease(lease.id)\n \n for tenant in allTenants:\n tenantObj = {\n 'id': tenant.id,\n 'name': tenant.first_name + ' ' + tenant.last_name,\n 'email': tenant.email,\n 'phone': tenant.phone\n \n }\n tenantsInfo.append(tenantObj)\n \n tenantsInfo = len(tenantsInfo) and tenantsInfo or 0\n \n transactionInfo = []\n if unit:\n transaction_q = model.Transaction.get_transactions_from_unit(unit.id)\n for transaction in transaction_q:\n date = transaction.date\n if transaction.income:\n transAmount = '$' + str('%.2f' % transaction.amount)\n else:\n transAmount = '- $' + str('%.2f' % transaction.amount)\n transObj = {\n 'type': transaction.type,\n 'amount': transAmount,\n 'income': transaction.income,\n 'month': date.month,\n 'day': date.day,\n 'year': date.year\n }\n transactionInfo.append(transObj)\n \n transactionInfo = len(transactionInfo) and transactionInfo or 0\n \n all_leases = []\n for l in leases:\n all_leases.append({'id':l.id, \n 'display':'{0} - {1}'.format(l.startdate.strftime(\"%B %d, %Y\"), \n l.outdate and l.outdate.strftime(\"%B %d, %Y\") or 'No date set')})\n # each row {id: asdf, display: asdf}\n unitDetails = {\n 'id': unit.id,\n 'label': unit.label,\n 'description': unit.description,\n 'floorplan': floorplanInfo,\n 'property': propertyInfo,\n 'tenants': tenantsInfo,\n 'currentLease': leaseInfo,\n 'lease': leaseInfo,\n 'leases': all_leases,\n 'transactions' : transactionInfo\n }\n \n return json.dumps(unitDetails)\n \n","sub_path":"build/lib.linux-x86_64-2.6/rentfox/controllers/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":15433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"521086","text":"# N = 1 일 때 케이스 생각해주어야 한다.\r\n# 자체루프가 생기는 경우를 생각해주어야 해\r\ntest = int(input())\r\nfor _ in range(test):\r\n N = int(input())\r\n arr = [0]\r\n for _ in range(N):\r\n arr.append(int(input()))\r\n # print(arr)\r\n cnt = 0\r\n i = 0\r\n if N == 1:\r\n print(1)\r\n exit()\r\n\r\n while cnt <= (N+1):\r\n\r\n cnt += 1\r\n if arr[i] == N:\r\n print(i)\r\n break\r\n i += 1\r\n print(i)\r\n print(cnt)\r\n print(0)","sub_path":"BAEKJOON/[baek] 11558 thegameofdeath.py","file_name":"[baek] 11558 thegameofdeath.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"638309558","text":"import sys\nimport os\nimport torch\nimport argparse\nfrom torch import optim\nfrom time import time\n\ntile2vec_dir = '/raid/users/ebarnett/tile2vec/'\nsys.path.append('../')\nsys.path.append(tile2vec_dir)\n\nfrom src.datasets import TileTripletsDataset, GetBands, RandomFlipAndRotate, ClipAndScale, ToFloatTensor, triplet_dataloader\nfrom src.tilenet import make_tilenet\nfrom src.training import prep_triplets, train_triplet_epoch\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--tile_dir', default='', type=str, help='Path to bigearthnet triplets')\n parser.add_argument('--model_dir', default='', type=str, help='Path to model saving')\n parser.add_argument('--batch_size', default=10, type=int, help='')\n parser.add_argument('--in_channels', default=12, type=int, help='12 for landsat')\n parser.add_argument('--shuffle', default=True, type=bool)\n parser.add_argument('--n_triplets', default=20000, type=int, help='size of dataset')\n parser.add_argument('--z_dim', default=512, type=int, help='dims of embedding space')\n parser.add_argument('--epochs', default=10, type=int, help='')\n parser.add_argument('--lr', default=0.01, type=float, help='')\n parser.add_argument('--margin', default=10, type=int, help='learning rate')\n parser.add_argument('--l2', default=0.01, type=float, help='learning rate')\n config = parser.parse_args()\n\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n cuda = torch.cuda.is_available()\n\n # Change these arguments to match your directory and desired parameters\n dataloader = triplet_dataloader(img_type = 'landsat',\n tile_dir = config.tile_dir,\n bands = config.in_channels,\n augment = True,\n batch_size = config.batch_size,\n shuffle = config.shuffle,\n num_workers = 4,\n n_triplets = config.n_triplets,\n pairs_only = True)\n print('Dataloader set up complete.')\n\n # Config the model\n TileNet = make_tilenet(in_channels=config.in_channels, z_dim=config.z_dim)\n TileNet.train()\n if cuda: TileNet.cuda()\n print('TileNet set up complete.')\n optimizer = optim.Adam(TileNet.parameters(), lr=config.lr, betas=(0.5, 0.999))\n\n print_every = 1000\n save_models = True\n\n if not os.path.exists(config.model_dir): os.makedirs(config.model_dir)\n\n t0 = time()\n print('Begin training.................')\n for epoch in range(0, config.epochs):\n (avg_loss, avg_l_n, avg_l_d, avg_l_nd) = \\\n train_triplet_epoch(model = TileNet,\n cuda = cuda,\n dataloader = dataloader,\n optimizer = optimizer,\n epoch = epoch+1,\n margin = config.margin,\n l2 = config.l2,\n print_every = print_every,\n t0 = t0)\n\n # Save model after last epoch\n if save_models:\n model_fn = os.path.join(config.model_dir, f'TileNet_epoch{config.epochs}.ckpt')\n torch.save(TileNet.state_dict(), model_fn)","sub_path":"train_benet.py","file_name":"train_benet.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616243226","text":"import unittest\nfrom zadaniepython import Vector,Matrix,MyError\n\nclass MatrixMethodTest(unittest.TestCase):\n \"\"\"\n Test matrix methods using black box pattern\n \"\"\"\n def test_constructor_for_correct_data(self):\n testArrays=[\n [[2,4,5],[5,6,2]],\n [[5,1,4],[3,7,3],[5,3,1]],\n [[4,2],[3,4]],\n [[]],\n [[3,4],[1,2],[4,1]]\n ]\n\n for array in testArrays:\n matrix=Matrix(array)\n self.assertEqual(matrix.table,array)\n self.assertEqual(matrix.__getDim__(),[len(array),len(array[0])])\n\n def test_constructor_for_wrong_data(self):\n testArrays=[\n [[2,3],[3]],\n [[3],[5,6]],\n [[],[3,4]]\n ]\n for array in testArrays:\n with self.assertRaises(MyError):\n Matrix(array)\n\n def test_add_operator_for_correct_data(self):\n testArraysAndResult=[\n ([[2,3],[1,2]],[[-7,-10],[-4,5]],[[-5,-7],[-3,7]]),\n ([[22, 3], [11, 20],[-5,-11]], [[-5, -17], [-9, 5],[-5,-8]],[[17,-14],[2,25],[-10,-19]]),\n ([[3,2,4],[-5,-3,-13]],[[4,3,12],[-4,-32,0]],[[7,5,16],[-9,-35,-13]]),\n #([],[],[])\n ]\n for first,second,expectedResult in testArraysAndResult:\n self.assertEqual((Matrix(first)+Matrix(second)).table,expectedResult)\n\n def test_add_operator_for_wrong_data(self):\n testArrays=[\n ([[-2,4],[3,4]],[[3,4],[4,5],[11,0]]),\n ([[3,5,2]],[[4,5]]),\n ([[4,2]],[[3,4,5]])\n ]\n for first,second in testArrays:\n with self.assertRaises(MyError):\n Matrix(first)+Matrix(second)\n\n def test_sub_operator_for_correct_data(self):\n testArraysAndResult=[\n ([[-5, -7], [-3, 7]],[[2, 3], [1, 2]], [[-7, -10], [-4, 5]] ),\n ([[17, -14], [2, 25], [-10, -19]],[[22, 3], [11, 20], [-5, -11]], [[-5, -17], [-9, 5], [-5, -8]]),\n ([[7, 5, 16], [-9, -35, -13]],[[3, 2, 4], [-5, -3, -13]], [[4, 3, 12], [-4, -32, 0]]),\n #([], [], [])\n ]\n\n for first,second,expectedResult in testArraysAndResult:\n self.assertEqual((Matrix(first)-Matrix(second)).table,expectedResult)\n\n def test_mul_operator_for_correct_data(self):\n testArraysAndValuesAndResults = [\n ([[3, -5, 7]], 3, [[9, -15, 21]]),\n ([[2, 3], [7, 2]], 2, [[4, 6], [14, 4]])\n ]\n for array, value, expected in testArraysAndValuesAndResults:\n result = Matrix(array) * value\n self.assertEqual(result.table,expected)\n\n testArraysAndResults=[\n ([[-5,4],[-4,5],[2,3]],[[0,2,4],[2,3,4]],[[8,2,-4],[10,7,4],[6,13,20]]),\n ([[-5, 4], [-4, 5]], [[0, 3, 3], [2, 4, 9]], [[8, 1, 21], [10, 8, 33]]),\n ([[1],[2],[3]],[4,5,6])\n ]\n\n for first,second,expected in testArraysAndResults:\n #print(Matrix(first).__str__()+\"\\n\\n\"+Matrix(second).__str__()+\"\\n\\n\"+Matrix(expected).__str__())\n result=(Matrix(first)*Matrix(second)).table\n self.assertEqual(result,expected)\n\n def test_mul_operator_for_wrong_size(self):\n testArrays=[\n ([[-5,4],[0,4]],[[3,4,5]]),\n ([[0],[-5],[7]],[[3],[8]]),\n ([[0,3,5],[7,3,2]],[[2,3]])\n ]\n\n for first,second in testArrays:\n with self.assertRaises(MyError):\n Matrix(first)*Matrix(second)\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"matrixTest.py","file_name":"matrixTest.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"280037621","text":"from flask import *\nimport time\nimport datetime\nimport pickle\nimport os.path\n\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\nimport pymysql\n\nimport config\n\nlistOfNames = []\napp = Flask(__name__, template_folder='HtmlPages/')\n# app.config['DEBUG'] = True\napp.config['TEMPLATES_AUTO_RELOAD'] = True\n\n# Connection info for database\nconnection = pymysql.connect(\n host=config.sqlServer.host,\n user=config.sqlServer.user,\n password=config.sqlServer.password,\n port=config.sqlServer.port,\n database=config.sqlServer.database,\n client_flag= pymysql.constants.CLIENT.MULTI_STATEMENTS,\n)\n\n@app.route('/', methods=['GET'])\ndef home():\n return render_template(\"home.html\")\n\n@app.route('/getnames', methods=['GET'])\ndef getNames():\n print(\"Getting names from the Google Sheet\")\n print(\"Downloading youth names...\")\n listOfNames = downloadYouthNames()\n print(\"Downloading facilitator names...\")\n listOfNames += downloadFacilitatorsNames()\n print(\"Name retrival complete.\")\n return jsonify(listOfNames)\n\n@app.route('/signin',methods=['POST'])\ndef signIn():\n print(\"Data: \",request.json)\n formData = json.loads(request.data)\n personName = formData[\"Name\"]\n signedUp = formData[\"SignedUp\"]\n\n #Backup sign in to csv\n if (os.path.exists(config.backupCSV.fileName)):\n backUpCSVFile = open(config.backupCSV.fileName,'a')\n else:\n backUpCSVFile = open(config.backupCSV.fileName,'w')\n backUpCSVFile.write(\"\\n\"+formData[\"Name\"]+\",\"+str(formData[\"SignedUp\"])+\",\"+datetime.datetime.now().isoformat())\n backUpCSVFile.close()\n print(\"Form values:\",(personName,signedUp,datetime.datetime.now().isoformat()))\n attendedToday = False if formData[\"Force\"] else check_attendance(personName)\n if attendedToday != False:\n print(\"Person allready attended\")\n return (jsonify(attendedToday),200)\n attendanceId = sql_insert_attendance(formData[\"Name\"],formData[\"SignedUp\"])\n if attendanceId != False:\n return (jsonify(attendanceId),200)\n else:\n return (\"\",400)\n\n@app.route('/deleteattendance', methods=['DELETE'])\ndef undo_attendance():\n print(\"Data: \",request.json)\n formData = json.loads(request.data)\n attendanceId = formData[\"id\"]\n if (sql_delete_attendance(attendanceId)):\n return (\"\",200)\n else:\n return (\"\",400)\n\ndef sql_delete_attendance(id):\n global connection\n connection.ping(reconnect=True)\n cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)\n query = \"Delete from attendance_record where attendance_id = (%s);\"\n try:\n cursor.execute(query, (id))\n connection.commit()\n return True\n except Exception as e:\n print(\"Attendance delete failed, Error:\", e)\n return False\n\ndef sql_insert_attendance(full_name,registered):\n global connection\n connection.ping(reconnect=True)\n cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)\n query = \"insert into qrl_membership_db.attendance_record (full_name, registered) values (%s,%s)\"\n \n try:\n cursor.execute(query, (full_name, registered))\n connection.commit()\n id = cursor.lastrowid\n print(\"Attendance:\",id)\n return {\n \"id\": id,\n \"attendance_warning\": False\n }\n except Exception as e:\n print(\"Attendance Insert failed, Error:\", e)\n return False\n\ndef check_attendance(full_name):\n global connection\n connection.ping(reconnect=True)\n cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)\n query = \"select * from attendance_record where arrival_time >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and full_name = %s order by arrival_time DESC;\"\n \n try:\n cursor.execute(query, (full_name))\n result = cursor.fetchone()\n print(\"Check attendance result:\",result)\n if result is not None:\n seconds_since_midnight = (datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()\n seconds_since_midnight_arrival = (result[\"arrival_time\"] - result[\"arrival_time\"].replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()\n if seconds_since_midnight < seconds_since_midnight_arrival:\n # Impossible situation, stops the un-needed warnings here\n return False\n return {\n \"id\": result[\"attendance_id\"],\n \"full_name\": result[\"full_name\"],\n \"previous_time\": result[\"arrival_time\"].strftime(\"%I:%M %p\"),\n \"attendance_warning\": True\n }\n else:\n return False\n except Exception as e:\n print(\"Attendance Insert failed, Error:\", e)\n return False\ndef downloadYouthNames():\n parsed = []\n try:\n #############\n #SETUP\n #############\n SCOPES = config.youthNameSheet.scopes\n SPREADSHEET_ID = config.youthNameSheet.spreadsheet_id\n\n RangeName = config.youthNameSheet.range_name\n creds = None\n\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(config.youthNameSheet.pickle_name):\n with open(config.youthNameSheet.pickle_name, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n config.youthNameSheet.credentials_name, SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(config.youthNameSheet.pickle_name, 'wb') as token:\n pickle.dump(creds, token)\n service = build('sheets', 'v4', credentials=creds)\n # Call the Sheets API\n sheet = service.spreadsheets()\n result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,range=RangeName).execute()[\"values\"]\n parsed = []\n print(result)\n for name in result: \n if len(name) > 0: \n parsed.append(name[0])\n except Exception as e:\n print(\"Failed to get google sheet, trying again in 5 seconds, error:\",e)\n time.sleep(5)\n downloadYouthNames()\n return parsed\n\ndef downloadFacilitatorsNames():\n parsed = []\n try:\n #############\n #SETUP\n #############\n SCOPES = config.facilitatorsNameSheet.scopes\n SPREADSHEET_ID = config.facilitatorsNameSheet.spreadsheet_id\n\n RangeName = config.facilitatorsNameSheet.range_name\n creds = None\n\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(config.facilitatorsNameSheet.pickle_name):\n with open(config.facilitatorsNameSheet.pickle_name, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n config.facilitatorsNameSheet.credentials_name, SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(config.facilitatorsNameSheet.pickle_name, 'wb') as token:\n pickle.dump(creds, token)\n service = build('sheets', 'v4', credentials=creds)\n # Call the Sheets API\n sheet = service.spreadsheets()\n result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,range=RangeName).execute()[\"values\"]\n parsed = []\n for name in result: \n if len(name) > 0: \n parsed.append(name[0])\n except Exception:\n print(\"Failed to get google sheet, trying again in 5 seconds\")\n time.sleep(5)\n downloadFacilitatorsNames()\n return parsed\n\napp.run(port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"377214728","text":"import FWCore.ParameterSet.Config as cms\n\necalBarrelDcsInfoTask = cms.EDAnalyzer(\"EBDcsInfoTask\",\n prefixME = cms.untracked.string('EcalBarrel'),\n enableCleanup = cms.untracked.bool(False),\n mergeRuns = cms.untracked.bool(False)\n)\n\n# from DQM.EcalCommon.dqmpset import *\n# from DQM.EcalCommon.CollectionTags_cfi import *\n# from DQM.EcalCommon.CommonParams_cfi import *\n\n# from DQM.EcalCommon.EcalDQMBinningService_cfi import *\n\n# import DQM.EcalBarrelMonitorTasks.TowerStatusTask_cfi as ecalTowerStatusTask\n\n# ecalMonitorTaskParams = dict(\n# TowerStatusTask = ecalTowerStatusTask.towerStatusTask,\n# Common = ecalCommonParams\n# )\n\n# ecalMonitorTaskPaths = dict(\n# TowerStatusTask = ecalTowerStatusTask.towerStatusTaskPaths\n# )\n\n# ecalBarrelDcsInfoTask = cms.EDAnalyzer(\"EcalDQMonitorTask\",\n# moduleName = cms.untracked.string(\"Ecal DCS Info\"),\n# # tasks to be turned on\n# tasks = cms.untracked.vstring(\n# \"TowerStatusTask\"\n# ),\n# # task parameters (included from indivitual cfis)\n# taskParameters = dqmpset(ecalMonitorTaskParams),\n# # ME paths for each task (included from inidividual cfis)\n# mePaths = dqmpaths(\"Ecal\", ecalMonitorTaskPaths),\n# collectionTags = ecalDQMCollectionTags,\n# allowMissingCollections = cms.untracked.bool(False),\n# verbosity = cms.untracked.int32(0)\n# )\n\n# ecalBarrelDcsInfoTask.taskParameters.TowerStatusTask.doDAQInfo = False\n# ecalBarrelDcsInfoTask.taskParameters.TowerStatusTask.doDAQInfo = True\n","sub_path":"DQM/EcalBarrelMonitorTasks/python/EBDcsInfoTask_cfi.py","file_name":"EBDcsInfoTask_cfi.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"110438909","text":"import cv2\nimport pytesseract\nimport unittest\n\n\ndef read_bubble_text_from_rect(map_image, bubble_rect, m=5):\n x, y, w, h = bubble_rect\n x, y, w, h = x + m, y + m, w - (2 * m), h - (2 * m)\n crop = map_image[y:y + h, x:x + w, :]\n return read_bubble_text(crop)\n\n\ndef read_bubble_text(crop_image):\n h, w, c = crop_image.shape\n crop_red = cv2.threshold(crop_image[:, :, 2], thresh=100, maxval=255, type=cv2.THRESH_BINARY_INV)[1]\n crop = crop_red\n crop = cv2.resize(crop, (w * 10, h * 10))\n crop = cv2.blur(crop, (7, 7))\n text = pytesseract.image_to_string(crop, config='--psm 6', lang='fra')\n text = text.replace('}', ')')\n text = text.replace('{', '(')\n return text[:-2]\n\n\nclass TestReadBubbleText(unittest.TestCase):\n def test_fight_bubble1(self):\n img = cv2.imread(\"/home/nicolas/Documents/Programation/Python/bot2pix/TestData/img/bubbleFight1.png\")\n target = \"Niveau 152\\n25 932 XP\\nMilimulou (28)\\nMilimulou (26)\\nMilimulou (24)\\nSanglier (28)\\n\" \\\n \"Ecurouille (24)\\nEcurouille (22)\"\n\n text = read_bubble_text(img)\n\n self.assertEqual(len(target), len(text))\n for c1, c2 in zip(text, target):\n self.assertEqual(c2, c1)\n\n def test_fight_bubble2(self):\n img = cv2.imread(\"/home/nicolas/Documents/Programation/Python/bot2pix/TestData/img/bubbleFight2.png\")\n target = \"Niveau 84\\n24 882 XP\\nÉcurouille (30)\\nPrespic (28)\\nPrespic (26)\"\n\n text = read_bubble_text(img)\n \n self.assertEqual(len(target), len(text))\n for c1, c2 in zip(text, target):\n self.assertEqual(c2, c1)\n\n def test_fight_bubble3(self):\n img = cv2.imread(\"/home/nicolas/Documents/Programation/Python/bot2pix/TestData/img/bubbleFight3.png\")\n target = \"Niveau 24\\n1 484 XP\\nPrespic (24)\"\n\n text = read_bubble_text(img)\n\n self.assertEqual(len(target), len(text))\n for c1, c2 in zip(text, target):\n self.assertEqual(c2, c1)\n\n\n","sub_path":"src/core/tools/image_processing/InfoBubbleReader.py","file_name":"InfoBubbleReader.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"356668026","text":"'''\r\n Follows every follower from a list of usernames (in toFollow.txt). If being rate-limited by Twitter,\r\n it will continuously wait and try again. This script is intended to be ran for long periods of time.\r\n'''\r\n\r\nimport bot\r\n\r\nif __name__ == '__main__':\r\n\r\n twitter = bot.TwitterAPI()\r\n twitter.followBot()\r\n","sub_path":"follow_bot.py","file_name":"follow_bot.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"237147846","text":"''' A toy example of playing Doudizhu with random agents in multi processes pool\n'''\n\nimport time\nimport random\nimport multiprocessing\n\nimport rlcard\nfrom rlcard.agents.random_agent import RandomAgent\nfrom rlcard.utils.utils import set_global_seed\n\nif __name__ == '__main__':\n start = time.time()\n # Avoid RuntimeError\n multiprocessing.freeze_support()\n\n # Initialize process pool\n pool = multiprocessing.Pool()\n\n # Make environment\n env = rlcard.make('doudizhu')\n episode_num = 1000\n\n # Set global seed\n set_global_seed(1)\n\n # Set up agents\n agent_0 = RandomAgent(action_num=env.action_num)\n agent_1 = RandomAgent(action_num=env.action_num)\n agent_2 = RandomAgent(action_num=env.action_num)\n env.set_agents([agent_0, agent_1, agent_2])\n\n trajectories_set = []\n for episode in range(episode_num):\n\n # Generate data from the environment\n result = pool.apply_async(env.run, args=(False, random.random()))\n trajectories_set.append(result)\n for result in trajectories_set:\n trajectories, player_wins = result.get()\n #print(trajectories, player_wins)\n end = time.time()\n pool.close()\n pool.join()\n print('run time:', end-start)\n","sub_path":"examples/doudizhu_multi.py","file_name":"doudizhu_multi.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"28240084","text":"import settings\nimport json\n\n__author__ = 'samgu'\n\n\nclass Cache(object):\n def __init__(self):\n self._data = {}\n self._ddata = {}\n cache_conf = settings.CACHE_CONF\n if cache_conf['type'] == 'json_file':\n self.cache_uri = cache_conf['uri']\n\n def _get_from_jsonfile(self):\n d = {}\n with open(self.cache_uri, 'r') as f:\n txt = f.read()\n self._data = json.loads(txt)\n\n def get(self, key):\n if not self._data:\n self._get_from_jsonfile()\n return self._data.get(key)\n\n\ncache = Cache()\n","sub_path":"src/utils/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99742613","text":"for _ in range(int(input())):\n [n, k] = [int(x) for x in input().split()]\n arr = [int(x) for x in input().split()]\n for i in range(n-1):\n val = arr[i+1] - arr[i] - 1\n if val != 0:\n if val >= k:\n print(arr[i] + k)\n break\n else:\n k -= val\n else:\n print(-1)\n","sub_path":"geeksforgeeks/basic/Kth_missing_element/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"30191265","text":"# Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character.\r\n\r\n# starting with empty lists\r\ndkey = []\r\ndvalue = []\r\n\r\nnum = int(input(\"\\nEnter the num of key-val pairs for the dict: \"))\r\n\r\nfor x in range(num):\r\n\tvar = input(f\"\\nEnter word {x} for the dict: \")\r\n\t# first char of var as a key\r\n\tdkey.append(var[0])\r\n\t# var as the value\r\n\tdvalue.append(var)\r\n\r\n# zip() makes an iterator that aggregates elements from each of the iterables(passed as args). No casting returns empty iterator. \r\n\r\n# Zip the lists together as a dict. Casting can be list or tuple also. Returns err for only 1 arg since dict needs 2.\r\nDict = dict(zip(dkey, dvalue))\r\n\r\nprint(f\"\\nDict created is: {Dict}\") ","sub_path":"create_dict.py","file_name":"create_dict.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"406840930","text":"import sys\nimport traceback\nfrom ext.MamUtils import MamUtils\nfrom ext.TargetFile import TargetFile\nfrom java.lang import StringBuffer\nfrom java.util import Properties\nfrom java.net import InetAddress\nfrom appilog.common.system.defines import AppilogTypes\nfrom appilog.collectors.services.dynamic.agents import AgentConstants\nfrom appilog.collectors.util import ProtocolDictionaryManager\nfrom appilog.collectors.util import NetworkXmlUtil\nfrom appilog.collectors.util import HostKeyUtil\nfrom appilog.common.utils import Protocol\n\nmam_utils = MamUtils('BusinessTransactionProgram.py')\n\n# 1 ##############################\t\nif mam_utils.isInfoEnabled():\n\tmam_utils.info('----- Start Transaction->Program')\n# 2 ##############################\n########################################### Oracle Data\nsid\t\t\t\t= Framework.getDestinationAttribute('database_sid')\nport\t\t\t\t= Framework.getDestinationAttribute('database_port')\nip\t\t\t\t= Framework.getDestinationAttribute('database_ip')\nhostId\t\t\t\t= Framework.getDestinationAttribute('hostId')\noracle_id\t\t\t\t= Framework.getDestinationAttribute('id')\ncredential_id\t\t\t\t= Framework.getDestinationAttribute('oracle_credential_id')\n########################################### ITG Data\nTABLE_USER \t\t\t= Framework.getDestinationAttribute('table_user')\nVIEW_NAME \t\t\t= Framework.getDestinationAttribute('view_name')\nTABLE_NAME \t\t\t= Framework.getDestinationAttribute('table_name')\nREQUEST_TYPE_NAME \t\t\t= Framework.getDestinationAttribute('request_type_name')\nRELATED_REQUEST_TYPE_NAME \t\t= Framework.getDestinationAttribute('related_request_type_name')\nRELATION_TYPE_NAME\t\t\t= Framework.getDestinationAttribute('relation_type_name')\nRELATION_PARENT_TYPE_NAME\t\t= Framework.getDestinationAttribute('relation_parent_type_name')\n########################################### MAM Data\nci_type\t\t\t\t= Framework.getDestinationAttribute('ci_type')\nsap_transaction_name\t\t\t= Framework.getDestinationAttribute('sap_transaction_name')\nmam_utils.info('----- Start Transaction->BusinessService')\n########################################### Object State Holder\noracleOSH \t\t\t\t= ObjectStateHolder('oracle', 6, oracle_id, AppilogTypes.CMDB_OBJECT_ID)\nsap_transaction_id\t\t\t= Framework.getDestinationAttribute('id')\nsap_transaction_program\t\t\t= Framework.getDestinationAttribute('program')\nsap_transactionOSH \t\t\t= ObjectStateHolder('sap_transaction', 6, sap_transaction_id, AppilogTypes.CMDB_OBJECT_ID)\nmam_utils.debug('----- Transaction OSH: ' ,sap_transactionOSH)\nmam_utils.debug('----- Transaction Name: ' ,sap_transaction_program)\nmam_utils.debug('----- Oracle OSH: ' ,oracleOSH)\nproperties \t\t\t= Properties()\nproperties.setProperty(Protocol.PROTOCOL_ATTRIBUTE_PORT, port)\nproperties.setProperty(Protocol.SQL_PROTOCOL_ATTRIBUTE_DBSID, sid)\ndbRelation=\"select ci.cmdb_id, des.a_data_name, ci.a_program from cmdb.cdm_sap_transaction_1 ci,cmdb.cdm_data_1 des where ci.cmdb_id=des.cmdb_id and des.a_data_name='%s' \"%(sap_transaction_name)\nmam_utils.debug('----- SQL: ' ,dbRelation)\n# 3 ##############################\ndef parseDbRelation(dbRelationRes):\n\t\tif dbRelationRes:\n\t\t\trows = dbRelationRes.getRowCount()\n\t\t\tcols = dbRelationRes.getColumnCount()\n\t\t\tif mam_utils.isDebugEnabled():\n\t\t\t\tmam_utils.debug('----- Number of Relations: ' , rows)\n\t\t\tfor row in range(rows):\n\t\t\t\tparentType\t\t= dbRelationRes.getCell(row, 0)\n\t\t\t\tparentType=parentType.replace(' ','_')\n\t\t\t\tparentID\t\t= dbRelationRes.getCell(row, 1)\n\t\t\t\tparentName\t\t= dbRelationRes.getCell(row, 2)\n\t\t\t\trelationID\t\t= dbRelationRes.getCell(row, 3)\n\t\t\t\trelationName\t\t= dbRelationRes.getCell(row, 4)\n\t\t\t\trelationName=relationName.replace(' ','_')\n\t\t\t\tchildType\t\t= dbRelationRes.getCell(row, 5)\n\t\t\t\tchildType=childType.replace(' ','_')\n\t\t\t\tchildID\t\t= dbRelationRes.getCell(row, 6)\n\t\t\t\tchildName\t\t= dbRelationRes.getCell(row, 7)\n\n\t\t\t\tsap_transactionOSH.setAttribute(AttributeStateHolder('data_name', parentName, 0, 'String'))\n\t\t\t\t##test=sap_transactionOSH.getAttributeValue('data_name')\n\t\t\t\t##mam_utils.debug('----- sap_transaction_Name ' , test)\n\t\t\t\t##sap_transactionOSH.setContainer('root_container', 'sap_resource')\n\t\t\t\tmam_utils.debug('----- sap_transactionOSH ' , sap_transactionOSH)\n\t\t\t\tdbChildOSH\t\t= ObjectStateHolder(childType,6)\t\n\t\t\t\tdbChildOSH.setAttribute(AttributeStateHolder('data_name', childName, 0,'String'))\n\t\t\t\tmam_utils.debug('----- dbChildOSH: ' , dbChildOSH)\n\t\t\t\tlinkOSH = HostKeyUtil.getLink('IS_TRANSACTION', sap_transactionOSH, dbChildOSH)\n\t\t\t\tOSHVSResult.add(linkOSH)\ndef discoverOracle(sqlAgent, ip, oracleOSH):\n\t\tdbRelationRes = doQuery(sqlAgent, dbRelation, ip)\n\t\tparseDbRelation(dbRelationRes)\ndef doQuery(sqlAgent, query, ip):\n\t\ttableRes = None\n\t\ttry:\n\t\t\ttableRes = sqlAgent.doTableCommand( query )\n\t\texcept:\n\t\t\tstacktrace = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])\n\t\t\tif mam_utils.isDebugEnabled():\n\t\t\t\tmam_utils.debug('Failed activating query: ' , query , '\\non destination: ' , ip , '\\nException:')\n\t\t\t\tmam_utils.debug(stacktrace)\n\t\tif mam_utils.isDebugEnabled():\n\t\t\tif tableRes:\n\t\t\t\trows = tableRes.getRowCount()\n\t\t\t\tcols = tableRes.getColumnCount()\n\t\t\t\tmam_utils.debug('Found ', rows, ' rows, ', cols, ' columns.')\t\n\t\t\treturn tableRes\n\n# 4 ##############################\ntry:\n\tsqlAgent = Framework.getAgent(AgentConstants.ORACLE_AGENT, ip , credential_id, properties)\nexcept:\n\tstacktrace = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])\n\tif mam_utils.isDebugEnabled():\n\t\tmam_utils.debug('Unexpected Framework.getAgent() Exception:')\n\t\tmam_utils.debug(stacktrace)\nelse:\n# 5 ##############################\n\tdiscoverOracle(sqlAgent, ip, oracleOSH)\n","sub_path":"HP-PPMC/uCMDB-specific/BusinessTransactionProgram.py","file_name":"BusinessTransactionProgram.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"129854269","text":"import math\r\nimport random\r\nfrom copy import deepcopy\r\n\r\n\r\n#possible improvements:\r\n#\tfind equations to replace every constant\r\n#\tallow every mutation instead of one at a time (add one for enable/disable)\r\n\r\n\r\n\r\n\r\nclass NeatNet:\r\n\r\n\tdef __init__ (self, inputNum, outputNum):\r\n\t\tself.noProgressLimit = 15 #number of times a network can fail to improve before dying, default 15\r\n\t\tself.genSize = 150 #number of genomes per generation\r\n\t\tself.goodGeneMultiplier = 3 #number of times more likely a good gene will be picked over the next best\r\n\r\n\r\n\r\n\t\tself.inputNum = inputNum\r\n\t\tself.outputNum = outputNum\r\n\r\n\t\tself.geneIdCounter = self.inputNum + self.outputNum + 1\r\n\t\tself.innovNumCounter = self.inputNum + 1\r\n\t\tself.generationInnovs = {'newNodes': [], 'newConnections': []}\r\n\t\t#newNodes : {'geneId': , 'input':inputNodeId, 'output':outputNodeId}\r\n\t\t#newConnections: {'innovNum': , 'input':inputNodeId, 'output':outputNodeId}\r\n\r\n\t\tself.generationCounter = 1\r\n\r\n\t\tself.resetGeneration()\r\n\r\n\t\tself.speciateGeneration()\r\n\t\tself.specLifeCounter = [[0,0] for i in range(len(self.speciesList))] #[counter,lastFitness]\r\n\r\n\tdef resetGeneration (self):\r\n\t\tself.speciesList = [[i for i in range(self.genSize)]]\r\n\t\t# gives index of every genome in generation for that species.\r\n\t\t# starts with all genomes in one species\r\n\t\tself.specLifeCounter = [[0,0] for i in range(len(self.speciesList))]\r\n\t\tself.generation = []\r\n\t\tfor counter in range(self.genSize):\r\n\t\t\tnodes = []\r\n\t\t\tconnections = []\r\n\t\t\tfor i in range(self.inputNum):\r\n\t\t\t\tnodes.append([i, 0]) #[geneId, nodeType] nodeTyp: 0=input, 1=bias, 2=hidden, 3=out\r\n\r\n\t\t\tnodes.append([len(nodes), 1])\r\n\r\n\t\t\tfor i in range(self.outputNum):\r\n\t\t\t\tnodes.append([len(nodes), 3])\r\n\r\n\t\t\tinnov = 0\r\n\t\t\tfor i in range(self.inputNum + 1):\r\n\t\t\t\tfor o in range(self.outputNum):\r\n\t\t\t\t\tweight = random.uniform(-3,3) #weights\r\n\t\t\t\t\tconnections.append([i, o+self.inputNum+1, weight, innov, True])\r\n\t\t\t\t\t\t# [inNode, outNode, weight, innovation#, enabled]\r\n\t\t\t\t\t\t# innovation increase for a given mutation only once a generation\r\n\t\t\t\t\t\t# innovation will always increase between generations\r\n\t\t\t\t\tinnov += 1\r\n\r\n\t\t\tnodeValue = [0 for i in range(len(nodes))] #output value of every node\r\n\t\t\tnodeValue[self.inputNum] = 1 #bias node always outputs 1\r\n\r\n\t\t\tself.generation.append({'nodes':nodes, 'connections':connections, \\\r\n\t\t\t\t'nodeValue':nodeValue})\r\n\r\n\r\n\tdef run (self, inputs, genMembNum):\r\n\t\tif len(inputs) != self.inputNum:\r\n\t\t\tprint(\"network needs \" + repr(self.inputNum) + \" inputs\")\r\n\t\t\texit(0)\r\n\r\n\t\t#normalize inputs\r\n\t\tsum = 0\r\n\t\tfor i in inputs:\r\n\t\t\tsum += i\r\n\t\tfor index,item in enumerate(inputs):\r\n\t\t\tif sum != 0:\r\n\t\t\t\tinputs[index] = item/sum\r\n\t\t\telse:\r\n\t\t\t\tinputs[index] = 0\r\n\t\t\t\r\n\t\ti=0\r\n\t\tfor index,item in enumerate(self.generation[genMembNum]['nodes']):\r\n\t\t\tif item[1] == 0:\r\n\t\t\t\tself.generation[genMembNum]['nodeValue'][index] = inputs[i]\r\n\t\t\t\ti += 1\r\n\r\n\t\tnodeSequence = [[i[0]] for i in self.generation[genMembNum]['nodes']]\r\n\t\t#nodes in same order and index as self.nodes and self.nodeValue\r\n\r\n\t\tfor i in range(len(self.generation[genMembNum]['connections'])): #put each connection input&weight into nodeSequence array\r\n\t\t\tif self.generation[genMembNum]['connections'][i][4]: #check if connection enabled\r\n\t\t\t\tinputNode = self.generation[genMembNum]['connections'][i][0]\r\n\t\t\t\toutputNode = self.generation[genMembNum]['connections'][i][1]\r\n\t\t\t\tweight = self.generation[genMembNum]['connections'][i][2]\r\n\r\n\t\t\t\tnodeIndex = 0\r\n\t\t\t\tfor index,item in enumerate(nodeSequence):\r\n\t\t\t\t\tif item[0] == outputNode:\r\n\t\t\t\t\t\tnodeIndex = index\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\tnodeSequence[nodeIndex].append([inputNode, weight])\r\n\t\t# end up with array of\r\n\t\t# nodeSequence[x] = [nodeID, [input1NodeID,weight1], [in2NodeID,weight2], ...]\r\n\r\n\t\tanswer = []\r\n\t\tfor index,node in enumerate(nodeSequence):\r\n\t\t\tif len(node) > 1: #exlude all input and offset nodes (inputs don't have input weight data)\r\n\t\t\t\tsumNodeValue = 0\r\n\t\t\t\tfor connection in node[1:]: #loops through every connection found on a node, calc node val\r\n\r\n\t\t\t\t\tfor index2,item2 in enumerate(self.generation[genMembNum]['nodes']): #find input node index to get output value from nodeValue\r\n\t\t\t\t\t\tif item2[0] == connection[0]:\r\n\t\t\t\t\t\t\tsumNodeValue += self.generation[genMembNum]['nodeValue'][index2] * connection[1]\r\n\r\n\t\t\t\tsumNodeValue = 1 / (1 + math.exp(-4.9*sumNodeValue)) # activation function, squishes output to 0-1, called a sigmoid transfer function (modified with 4.9)\r\n\t\t\t\tif self.generation[genMembNum]['nodes'][index][1] == 3:\r\n\t\t\t\t\tanswer.append(sumNodeValue)\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.generation[genMembNum]['nodeValue'][index] = sumNodeValue\r\n\r\n\t\tanswerIndex = 0\r\n\t\tfor index, item in enumerate(self.generation[genMembNum]['nodes']):\r\n\t\t\t#writes output nodes results to nodeValue last to ensure there's no recursion on outputs\r\n\t\t\tif item[1] == 3:\r\n\t\t\t\tself.generation[genMembNum]['nodeValue'][index] = answer[answerIndex]\r\n\t\t\t\tanswerIndex +=1\r\n\t\treturn answer\r\n\r\n\r\n\tdef findFitness(self, inputs, solutions, genMembNum):\r\n\t\ttotalDist = 0\r\n\t\troundDist = 0\r\n\t\tfor index, item in enumerate(inputs):\r\n\t\t\ttestAnswer = self.run(item, genMembNum)\r\n\r\n\t\t\ttotalDist += abs(testAnswer[0]-solutions[index][0])\r\n\t\t\troundDist += abs(round(testAnswer[0])-solutions[index][0])\r\n\r\n\t\tfitness = ((4 - totalDist)/4)**2\r\n\r\n\t\tif roundDist == 0:\r\n\t\t\tprint(fitness, \"testing\")\r\n\t\t\tfitness = 1\r\n\r\n\t\tself.resetNodeValues(genMembNum)\r\n\t\treturn fitness\r\n\r\n\r\n\tdef breedNet (self, parent1, parent2, equalFitness = False):\r\n\t#parent1 assumed to be most fit\r\n\r\n\t#always include the excess and disjoints of the fittest genome. Randomly select weights for matched genes between the two parents.\r\n\r\n\t\tgenomeComparison = self.compareGenomes(parent1, parent2)\r\n\t\t# add breeding logic here. All mutation stuff comes after they've bred.\r\n\r\n\t\tconnections = []\r\n\t\tnodes = deepcopy(parent1['nodes'])\r\n\r\n\r\n\t\tif parent1 == parent2:\r\n\t\t\tchild = deepcopy(parent1)\r\n\t\t\tchild['nodeValue'] = None\r\n\t\telse:\r\n\t\t\tif equalFitness:\r\n\t\t\t\tfor index1, node1 in enumerate(genomeComparison['parent2']['uniqueNodes']):\r\n\t\t\t\t\tfor i in range(len(parent2['nodes'])):\r\n\t\t\t\t\t\tif parent2['nodes'][i][0] == node1[0]:\r\n\t\t\t\t\t\t\tn = 1\r\n\t\t\t\t\t\t\tfoundInputNode = False\r\n\t\t\t\t\t\t\twhile not foundInputNode:\r\n\t\t\t\t\t\t\t\tinputNode = parent2['nodes'][i-n][0]\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\tfor index2, node2 in enumerate(nodes):\r\n\t\t\t\t\t\t\t\t\tif node2[0] == inputNode:\r\n\t\t\t\t\t\t\t\t\t\tnodes.insert(index2+1, node1)\r\n\t\t\t\t\t\t\t\t\t\tfoundInputNode = True\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\tn = n + 1\r\n\t\t\t\t\t\t\tbreak\r\n\r\n\r\n\t\t\tmatchedConnections = []\r\n\t\t\tfor index,item in enumerate(genomeComparison['parent1']['match']):\r\n\t\t\t\tmatchedConnections.append([item])\r\n\t\t\tfor index,item in enumerate(genomeComparison['parent2']['match']):\r\n\t\t\t\tmatchedConnections[index].append(item)\r\n\r\n\t\t\tfor i in range(len(matchedConnections)):\r\n\t\t\t\tgeneParent = random.randint(0,1)\r\n\t\t\t\tconnections.append(matchedConnections[i][geneParent])\r\n\t\t\t\tif matchedConnections[i][0][4] == False or matchedConnections[i][1][4] == False:\r\n\t\t\t\t\tdisableChance = random.randint(1,100)\r\n\t\t\t\t\tif disableChance >= 75: #75% inherited gene disabled if disabled in either parent\r\n\t\t\t\t\t\tconnections[len(connections)-1][4] = False\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tconnections[len(connections)-1][4] = True\r\n\r\n\t\t\tconnections = connections + genomeComparison['parent1']['disjoint']\r\n\t\t\tconnections = connections + genomeComparison['parent1']['excess']\r\n\r\n\r\n\r\n\t\t\tchild = {'nodes':nodes, 'connections':connections, 'nodeValue':None} #nodeValue only used in solving\r\n\r\n\t\t#80% connection weight mutation\r\n\t\t\t#90% uniformly perturbed\r\n\t\t\t#10% new random value\r\n\t\tmutationSelect = random.randint(1,100)\r\n\t\tif mutationSelect <= 80:\r\n\t\t\tconnectionSelect = random.randint(0,len(child['connections'])-1)\r\n\t\t\tchild['connections'][connectionSelect][4] = True\r\n\t\t\tlocalitySelect = random.randint(1,100)\r\n\t\t\tif localitySelect <=10: #new random value\r\n\t\t\t\tchild['connections'][connectionSelect][2] = random.uniform(-3,3) #weights\r\n\t\t\telse: #localy perturbed\r\n\t\t\t\tweight = child['connections'][connectionSelect][2]\r\n\t\t\t\tchild['connections'][connectionSelect][2] = random.uniform(-.1,.1) * weight + weight\r\n\t\t\t\t#local purturbation of weight is +- 10%\r\n\t\t\t\tif weight == 0:\r\n\t\t\t\t\tchild['connections'][connectionSelect][2] = random.uniform(-.01,.01)\r\n\t\t#3% adding new node\r\n\t\telif 81 <= mutationSelect <= 83:\r\n\t\t\trandConnection = random.randint(0,len(child['connections'])-1)\r\n\t\t\tgene = child['connections'][randConnection]\r\n\t\t\tinputNode = gene[0] #geneId of node\r\n\t\t\toutputNode = gene[1]\r\n\r\n\t\t\t# All new nodes and connection made in the same place in the same generation should have the same generID and innovations\r\n\t\t\tnodeId = 0\r\n\t\t\tfor index,item in enumerate(self.generationInnovs['newNodes']):\r\n\t\t\t\tif item['input'] == inputNode and item['output'] == outputNode:\r\n\t\t\t\t\tnodeId = item['geneId']\r\n\t\t\t\t\tbreak;\r\n\t\t\tif nodeId == 0:\r\n\t\t\t\tself.geneIdCounter += 1\r\n\t\t\t\tnodeId = self.geneIdCounter\r\n\t\t\t\tself.generationInnovs['newNodes'].append({'input':inputNode, 'output':outputNode, 'geneId':nodeId})\r\n\r\n\t\t\tinnovNumInput = 0\r\n\t\t\tinnovNumOutput = 0\r\n\t\t\tfor index,item in enumerate(self.generationInnovs['newConnections']):\r\n\t\t\t\tif item['input'] == inputNode and item['output'] == nodeId:\r\n\t\t\t\t\tinnovNumInput = item['innovNum']\r\n\t\t\t\tif item['input'] == nodeId and item['output'] == outputNode:\r\n\t\t\t\t\tinnovNumOutput = item['innovNum']\r\n\t\t\tif innovNumInput == 0:\r\n\t\t\t\tself.innovNumCounter += 1\r\n\t\t\t\tinnovNumInput = self.innovNumCounter\r\n\t\t\t\tself.generationInnovs['newConnections'].append({'input':inputNode, 'output':nodeId, 'innovNum':innovNumInput})\r\n\t\t\tif innovNumOutput == 0:\r\n\t\t\t\tself.innovNumCounter += 1\r\n\t\t\t\tinnovNumOutput = self.innovNumCounter\r\n\t\t\t\tself.generationInnovs['newConnections'].append({'input':nodeId, 'output':outputNode, 'innovNum':innovNumOutput})\r\n\r\n\t\t\t#create new node and disable connection. Add two new connections. connection into new node gets weight of 1, connection out gets weight of original connection\r\n\t\t\tchild['connections'][randConnection][4] = False\r\n\t\t\tnewConnection1 = [inputNode, nodeId, 1, innovNumInput, True]\r\n\t\t\tchild['connections'].append(newConnection1)\r\n\r\n\t\t\tweight = child['connections'][randConnection][2]\r\n\t\t\tnewConnection2 = [nodeId, outputNode, weight, innovNumOutput, True]\r\n\t\t\tchild['connections'].append(newConnection2)\r\n\r\n\t\t\tfor index,item in enumerate(child['nodes']):\r\n\t\t\t\tif item[0] == inputNode:\r\n\t\t\t\t\tchild['nodes'].insert(index+1, [nodeId, 2])\r\n\t\t\t\t\tbreak\r\n\r\n\t\t#5% new connection (30% for larger population)\r\n\t\telif 84 <= mutationSelect <= 89:\r\n\t\t\trandNodeInput = random.randint(0,len(child['nodes'])-1)\r\n\t\t\twhile True:\r\n\t\t\t\trandNodeOutput = random.randint(0,len(child['nodes'])-1)\r\n\t\t\t\tif child['nodes'][randNodeOutput][1] <= 2:\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tinnovNum = 0\r\n\t\t\tfor index,item in enumerate(self.generationInnovs['newConnections']):\r\n\t\t\t\tif item['input'] == randNodeInput and item['output'] == randNodeOutput:\r\n\t\t\t\t\tinnovNum = item['innovNum']\r\n\t\t\t\t\tbreak\r\n\t\t\tif innovNum == 0:\r\n\t\t\t\tself.innovNumCounter += 1\r\n\t\t\t\tinnovNum = self.innovNumCounter\r\n\t\t\t\tself.generationInnovs['newConnections'].append({'input':randNodeInput, 'output':randNodeOutput, 'innovNum':innovNum})\r\n\r\n\t\t\tconnectionExists = False\r\n\t\t\tfor index,item in enumerate(child['connections']):\r\n\t\t\t\tif randNodeInput == item[0] and randNodeOutput == item[1]:\r\n\t\t\t\t\tconnectionExists = True\r\n\t\t\t\t\tself.innovNumCounter -= 1\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tif not connectionExists:\r\n\t\t\t\tweight = random.uniform(-3,3) #weights\r\n\t\t\t\tchild['connections'].append([randNodeInput, randNodeOutput, weight, innovNum, True])\r\n\r\n\t\tchild['nodeValue'] = [0 for i in range(len(child['nodes']))] #output value of every node\r\n\t\tfor index, item in enumerate(child['nodes']):\r\n\t\t\tif item[1] == 1:\r\n\t\t\t\tchild['nodeValue'][index] = 1\r\n\t\t\t\tbreak\r\n\r\n\t\treturn child\r\n\r\n\r\n\tdef createGeneration(self, speciesFitnessData):\r\n\t\tself.generationInnovs = {'newNodes': [], 'newConnections': []}\r\n\r\n\t\t#species that don't improve after 15 generations should die\r\n\t\topenPositions = 0\r\n\t\tdeleteList = []\r\n\t\tfor index,item in enumerate(speciesFitnessData):\r\n\t\t\tif item[-1][1] <= self.specLifeCounter[index][1]:\r\n\t\t\t\tself.specLifeCounter[index][0] += 1\r\n\t\t\t\tif self.specLifeCounter[index][0] >= self.noProgressLimit:\r\n\t\t\t\t\topenPositions += len(self.speciesList[index])\r\n\t\t\t\t\tdeleteList.append(index)\r\n\t\t\telse:\r\n\t\t\t\tself.specLifeCounter[index][0] = 0\r\n\t\t\t\tself.specLifeCounter[index][1] = item[-1][1]\r\n\r\n\t\tfor index,item in enumerate(deleteList):\r\n\t\t\tdel self.speciesList[item-index]\r\n\t\t\tdel self.specLifeCounter[item-index]\r\n\t\t\tdel speciesFitnessData[item-index]\r\n\r\n\t\t#if last species is deleted generate new random network\r\n\t\tif openPositions == len(self.generation):\r\n\t\t\tprint('reset')\r\n\t\t\tself.resetGeneration()\r\n\t\t\treturn None\r\n\r\n\t\tif openPositions !=0:\r\n\t\t\tspeciesNum = len(self.speciesList)\r\n\t\t\taddMembers = [math.floor(openPositions/speciesNum) for i in range(speciesNum)]\r\n\t\t\tfor i in range(openPositions%speciesNum):\r\n\t\t\t\taddMembers[0] += 1\r\n\r\n\t\t#each species should inter breed a proportional amount of the population (should make as many children as species currently has)\r\n\t\t#use explicit fitness sharing to determine proportion of offsping each member should have of species\r\n\t\tnewGeneration = []\r\n\t\tfor specIndex,specItem in enumerate(speciesFitnessData):\r\n\t\t\tm=0\r\n\t\t\tif openPositions !=0:\r\n\t\t\t\tm = addMembers[specIndex]\r\n\t\t\tfor i in range(len(specItem)+m):\r\n\t\t\t\t#champion of 5>= species is copied to new generation unchanged\r\n\t\t\t\tif len(specItem) >= 5 and i == 0:\r\n\t\t\t\t\tnewGeneration.append(self.generation[specItem[-1][0]])\r\n\t\t\t\t\tcontinue\r\n\r\n\t\t\t\t#between species mating rate .1%\r\n\t\t\t\tx = self.goodGeneMultiplier #each fittest genome has x times the chance of being picked as the next\r\n\t\t\t\tif random.randint(1,1000) == 1 and len(speciesFitnessData) > 1:\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\tspecIndex2 = random.randint(0,len(speciesFitnessData)-1)\r\n\t\t\t\t\t\tif specIndex2 != specIndex:\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\tparentIndex2 = round(math.log(random.randint(1,x**(len(speciesFitnessData[specIndex2])-1)),x))\r\n\t\t\t\t\tparent2 = self.generation[speciesFitnessData[specIndex2][parentIndex2][0]]\r\n\t\t\t\t\tparent2Fitness = speciesFitnessData[specIndex2][parentIndex2][1]\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tparentIndex2 = round(math.log(random.randint(1,x**(len(specItem)-1)),x))\r\n\t\t\t\t\tparent2 = self.generation[specItem[parentIndex2][0]]\r\n\t\t\t\t\tparent2Fitness = specItem[parentIndex2][1]\r\n\r\n\t\t\t\tparentIndex1 = round(math.log(random.randint(1,x**(len(specItem)-1)),x))\r\n\t\t\t\t#math ceil and log2 decode random number into parentIndex1 = genome index\r\n\t\t\t\tparent1 = self.generation[specItem[parentIndex1][0]]\r\n\r\n\t\t\t\tif specItem[parentIndex1][1]==parent2Fitness:\r\n\t\t\t\t\tnewGeneration.append(self.breedNet(parent1,parent2,True))\r\n\t\t\t\telif specItem[parentIndex1][1]>=parent2Fitness:\r\n\t\t\t\t\tnewGeneration.append(self.breedNet(parent1,parent2))\r\n\t\t\t\telse:\r\n\t\t\t\t\tnewGeneration.append(self.breedNet(parent2,parent1))\r\n\r\n\t\tself.generation = newGeneration\r\n\t\t#25% offspring from mutation w/o crossover\r\n\r\n\r\n\tdef resetNodeValues(self, genomeNum):\r\n\t\tarraySize = len(self.generation[genomeNum]['nodeValue'])\r\n\t\tself.generation[genomeNum]['nodeValue'] = [0 for i in range(arraySize)]\r\n\r\n\t\tfor index, item in enumerate(self.generation[genomeNum]['nodes']):\r\n\t\t\tif item[1] == 1:\r\n\t\t\t\tself.generation[genomeNum]['nodeValue'][index] = 1\r\n\t\t\t\tbreak\r\n\r\n\tdef speciateGeneration(self):\r\n\t\tthreshold = 3.0# change to tune network, default 3\r\n\t\tN =1 #For # of connections < 20 in largest genome N=1, N is # of genes in largest genome\r\n\t\tc1 = 1\r\n\t\tc2 = 1\r\n\t\tc3 = .4 #0.4\r\n\r\n\t\tspeciesReps = [];\r\n\t\tfor index, array in enumerate(self.speciesList): #grabs one from each old species\r\n\t\t\trandIndex = array[random.randint(0,len(array)-1)]\r\n\t\t\tspeciesReps.append(self.generation[randIndex])\r\n\r\n\t\tself.speciesList = [[] for i in range(len(speciesReps))]\r\n\t\tfor index,item in enumerate(self.generation):\r\n\t\t\tfor index2, item2 in enumerate(speciesReps):\r\n\t\t\t\t#find # of disjoint nodes, genes, and average weight differences between rep and new gene\r\n\r\n\t\t\t\tcompared = self.compareGenomes(item, item2)\r\n\t\t\t\tdistance = c1*compared['excess']/N + c2*compared['disjoint']/N \\\r\n\t\t\t\t+ c3*compared['avgWeight']\r\n\r\n\t\t\t\t# if distance is less than threshold add item to self.speciesList[index2] and break.\r\n\t\t\t\tif distance < threshold:\r\n\t\t\t\t\tself.speciesList[index2].append(index)\r\n\t\t\t\t\tbreak\r\n\t\t\t\t# if no match make new species\r\n\t\t\t\tif index2 == len(speciesReps)-1:\r\n\t\t\t\t\tself.speciesList.append([index])\r\n\t\t\t\t\tself.specLifeCounter.append([0,0])\r\n\r\n\t\t#remove any empty species\r\n\t\tdeleteList = []\r\n\t\tfor index,item in enumerate(self.speciesList):\r\n\t\t\tif len(item) == 0:\r\n\t\t\t\tdeleteList.append(index)\r\n\t\tfor index,item in enumerate(deleteList):\r\n\t\t\tdel self.speciesList[item-index]\r\n\r\n\r\n\tdef compareGenomes(self, genome1, genome2):\r\n\r\n\t\t#find highest inov # for genome with lowest max inov\r\n\t\tmax1 = 0\r\n\t\tfor index, item in enumerate(genome1['connections']):\r\n\t\t\tif item[3] > max1:\r\n\t\t\t\tmax1 = item[3]\r\n\t\tmax2 = 0\r\n\t\tfor index, item in enumerate(genome2['connections']):\r\n\t\t\tif item[3] > max2:\r\n\t\t\t\tmax2 = item[3]\r\n\t\texcessInovLimit = max1 if max1 < max2 else max2 #Last inov # that isn't an excess inov\r\n\r\n\t\tparent1 = {'match':[], 'disjoint':[], 'excess':[], 'uniqueNodes':[]}\r\n\t\tparent2 = {'match':[], 'disjoint':[], 'excess':[], 'uniqueNodes':[]} # first 3 are connections\r\n\r\n\t\t#find similar, disjoint, and excess connections\r\n\t\tsimilar = []\r\n\t\tdisjoint = 0\r\n\t\texcess = 0;\r\n\t\tfor index, item in enumerate(genome1['connections']):\r\n\t\t\thasMatch = False\r\n\t\t\tfor index2, item2 in enumerate(genome2['connections']):\r\n\t\t\t\tif item[3] == item2[3]:\r\n\t\t\t\t\tsimilar.append([item[2], item2[2]])\r\n\t\t\t\t\thasMatch = True\r\n\t\t\t\t\tparent1['match'].append(item)\r\n\t\t\t\t\tparent2['match'].append(item2)\r\n\t\t\t\t\tbreak\r\n\t\t\tif not hasMatch and item[3] <= excessInovLimit:\r\n\t\t\t\tparent1['disjoint'].append(item)\r\n\t\t\t\tdisjoint += 1\r\n\t\t\telif not hasMatch and item[3] > excessInovLimit:\r\n\t\t\t\tparent1['excess'].append(item)\r\n\t\t\t\texcess += 1\r\n\r\n\t\tfor index, item in enumerate(genome2['connections']):\r\n\t\t\thasMatch = False\r\n\t\t\tfor index2, item2 in enumerate(genome1['connections']):\r\n\t\t\t\tif item[3] == item2[3]:\r\n\t\t\t\t\thasMatch = True\r\n\t\t\t\t\tbreak\r\n\t\t\tif not hasMatch and item[3] <= excessInovLimit:\r\n\t\t\t\tparent2['disjoint'].append(item)\r\n\t\t\t\tdisjoint += 1\r\n\t\t\telif not hasMatch and item[3] > excessInovLimit:\r\n\t\t\t\tparent2['excess'].append(item)\r\n\t\t\t\texcess += 1\r\n\r\n\t\tlocalAvg = []\r\n\t\tfor index, item in enumerate(similar):\r\n\t\t\tlocalAvg.append(abs(item[0]-item[1]))\r\n\t\tavg = sum(localAvg) / float(len(localAvg))\r\n\r\n\t\t#find unique nodes\r\n\t\tfor item in enumerate(genome1['nodes']):\r\n\t\t\thasMatch = False\r\n\t\t\tfor item2 in enumerate(genome2['nodes']):\r\n\t\t\t\tif item[0] == item2[0]:\r\n\t\t\t\t\thasMatch = True\r\n\t\t\t\t\tbreak\r\n\t\t\tif hasMatch == False:\r\n\t\t\t\tparent1['uniqueNodes'].append(item)\r\n\r\n\t\tfor item in enumerate(genome2['nodes']):\r\n\t\t\thasMatch = False\r\n\t\t\tfor item2 in enumerate(genome1['nodes']):\r\n\t\t\t\tif item[0] == item2[0]:\r\n\t\t\t\t\thasMatch = True\r\n\t\t\t\t\tbreak\r\n\t\t\tif hasMatch == False:\r\n\t\t\t\tparent2['uniqueNodes'].append(item)\r\n\r\n\t\treturn {'avgWeight': avg, 'disjoint': disjoint, 'excess':excess, \\\r\n\t\t'parent1':parent1, 'parent2':parent2}\r\n\t\t# {'avgWeight': weight average, 'disjoint': number of disjoints,\r\n\t\t# 'excess': number of excess, 'parent1':parent1, 'parent2':parent2}\r\n\t\t#\t\tparent = {'match':[], 'disjoint':[], 'excess':[], 'uniqueNodes':[]}\r\n\r\n\r\n\r\n\tdef evolveNet(self, trainingData, trainingAnswers, minFitnessNeeded):\r\n\t\twhile True:\r\n\r\n\t\t\t#find fitness of every member, first parent in breedNet is fitest:\r\n\t\t\t#loop that uses self.breednet to create self.genSize # of new genomes for new gen.\r\n\t\t\tfitness = 0\r\n\t\t\tspeciesFitnessData = []\r\n\t\t\tfor specIndex,specItem in enumerate(self.speciesList):\r\n\t\t\t\tspeciesFitnessData.append([])\r\n\t\t\t\tfor index,item in enumerate(specItem):\r\n\t\t\t\t\tfitness = self.findFitness(trainingData, trainingAnswers, item)\r\n\t\t\t\t\tspeciesFitnessData[specIndex].append([item,fitness])\r\n\t\t\t#store new gen locally until end when self.generation and self.speciesList are over written\r\n\r\n\t\t\t#use explicit fitness sharing to determine proportion of offsping each member should have of species\r\n\t\t\tadjustedFitnessData = deepcopy(speciesFitnessData)\r\n\t\t\tfor specIndex,specItem in enumerate(adjustedFitnessData):\r\n\t\t\t\tfor index,item in enumerate(specItem):\r\n\t\t\t\t\tfitnessSharingAdjust = item[1]/len(specItem)\r\n\t\t\t\t\tadjustedFitnessData[specIndex][index][1] = fitnessSharingAdjust\r\n\r\n\t\t\t#sort from weakest to fittest genome in species\r\n\t\t\tfor specIndex in range(len(adjustedFitnessData)):\r\n\t\t\t\tfor index in range(len(adjustedFitnessData[specIndex])-1):\r\n\t\t\t\t\tweakestGenome = deepcopy(adjustedFitnessData[specIndex][index])\r\n\t\t\t\t\treplaceIndex = index\r\n\t\t\t\t\tfor genoIndex in range(index+1,len(adjustedFitnessData[specIndex])):\r\n\t\t\t\t\t\tif adjustedFitnessData[specIndex][genoIndex][1] <= weakestGenome[1]:\r\n\t\t\t\t\t\t\tweakestGenome = deepcopy(adjustedFitnessData[specIndex][genoIndex])\r\n\t\t\t\t\t\t\treplaceIndex = genoIndex\r\n\t\t\t\t\tadjustedFitnessData[specIndex][replaceIndex] = adjustedFitnessData[specIndex][index]\r\n\t\t\t\t\tadjustedFitnessData[specIndex][index] = weakestGenome\r\n\r\n\t\t\t#test each member of generation with other set of data/answers\r\n\t\t\t#find highest fitness of new generation\r\n\t\t\t#compare fitness to desired fitness\r\n\t\t\tmaxFitness = 0\r\n\t\t\tfittestIndex = 0\r\n\r\n\t\t\tfor specIndex,specItem in enumerate(speciesFitnessData):\r\n\t\t\t\tfor index,item in enumerate(specItem):\r\n\t\t\t\t\tif item[1] > maxFitness:\r\n\t\t\t\t\t\tmaxFitness = item[1]\r\n\t\t\t\t\t\tfittestIndex = item[0]\r\n\r\n\r\n\t\t\tprint(maxFitness, \" \", self.generationCounter, len(adjustedFitnessData))\r\n\t\t\tif maxFitness >= minFitnessNeeded:\r\n\t\t\t\tfitness = self.findFitness(trainingData, trainingAnswers, fittestIndex)\r\n\t\t\t\tprint(fitness)\r\n\t\t\t\treturn [self.generation[fittestIndex],fittestIndex, self.generationCounter, maxFitness]\r\n\r\n\r\n\t\t\t#if not reached loop this function\r\n\r\n\t\t\tself.createGeneration(adjustedFitnessData)\r\n\t\t\tself.speciateGeneration()\r\n\t\t\t#increase generation counter\r\n\t\t\tself.generationCounter += 1\r\n","sub_path":"neatnet.py","file_name":"neatnet.py","file_ext":"py","file_size_in_byte":21877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"306113521","text":"\n\ndef dfs(now_pos):\n global cnt;\n cnt+=1\n visited[now_pos] = True\n for next_pos in adj[now_pos]:\n if not visited[next_pos]:\n dfs(next_pos)\n\nif __name__ == '__main__':\n\n n = int(input())\n m = int(input())\n\n adj = [[] for _ in range(n+1)]\n visited = [False] * (n+1)\n cnt = 0\n\n for _ in range(m):\n x,y = map(int,input().split())\n adj[x].append(y)\n adj[y].append(x)\n\n\n dfs(1)\n print(cnt-1)","sub_path":"패스트캠퍼스/유형별문제풀이/그래프/바이러스2606.py","file_name":"바이러스2606.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"18137100","text":"import tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport tornado.template\nfrom tornado.escape import *\n\nimport csv\nimport json\nimport os\nimport os.path\nimport sys\nimport datetime\nimport time\nimport uuid\nimport redis\n\n# ******************************************************************************\n# Setting up some globals ******************************************************\nprint(\"\\n*************Starting Tornado Web Service**************\\n\")\n\n#Some can be read from Environmental variables (or not as they have a default)\nBASE_PATH = os.getenv(\"BASE_PATH\", \"\")\nprint(\"BASE_PATH: \" + BASE_PATH)\n\n# If WEB_SITE_PORT not redefined as an Environmental Variable us 9001\nWEB_SITE_PORT = int(os.getenv('WEB_SITE_PORT', '9001'))\nprint(\"WEB PORT:\", WEB_SITE_PORT)\nREDIS_IP_ADDRESS = os.getenv(\"REDIS_IP_ADDRESS\", \"localhost\")\nprint(\"REDIS IP ADDRESS:\", REDIS_IP_ADDRESS)\nprint(file = sys.stderr)\nprint()\n\n# These control how quickly websockets refresh\nWEBSOCKET_REFRESH_RATE_MS = 10000\n\n# Logging function good for debugging and recording events of importance.\n# In a real system these might point to some thing besides printing the stdout\ndef applog(*a):\n print(*a, file = sys.stderr)\n\n# ******************************************************************************\n# **** Base Handler ************************************************************\n\nclass BaseHandler(tornado.web.RequestHandler):\n # This base handler is an extension of the orginal request handler to add\n # some features\n def get_current_user(self):\n return self.get_secure_cookie(\"user\")\n\n def get_current_role(self):\n return self.get_secure_cookie(\"role\")\n\n def isWriteAllowed(self):\n writeAllowed = ('\"ADMIN\"' in self.get_current_role()) or ('\"WRITE\"' in self.get_current_role())\n return(writeAllowed)\n\n def isAdminAllowed(self):\n adminAllowed = ('\"ADMIN\"' in self.get_current_role())\n return(adminAllowed)\n\n def returnError(self,error,write):\n # Create a JSON object\n resp_obj = {}\n resp_obj['rmessage'] = error\n resp_obj['status'] = error\n applog(error)\n # Send object back as response\n write(json.dumps(resp_obj))\n\n# ******************************************************************************\n# ******************************************************************************\n# WebSocket Handler\n\ndef add_interaction_to_redis(redis_client, interaction, count):\n # Add source to data\n interaction[\"src-id\"] = \"web\"\n #********************************\n # Take the string and publish to ui-stream on REDIS\n message = json.dumps(interaction)\n redis_client.publish('ui-stream', message)\n #********************************\n # Set a key value in Redis\n # Create the key in this order\n pref_order = [\"src-id\", \"product-id\", \"product-name\", \"interaction-type\", \"timestamp\"]\n list_to_join = []\n for field in pref_order:\n value = str(interaction[field])\n value = value.replace(\":\", \"_\") # Filter out any delimiter characters\n list_to_join.extend([field, value])\n entry_key = ':'.join(list_to_join) # Create the entry key\n # Send this to Redis\n redis_client.set(entry_key, count)\n #********************************\n # ZADD this to a set to make searching by datetime easier\n score = int(interaction['timestamp'])\n scored_data = entry_key\n z_key = \"web_ts\"\n redis_client.zadd(z_key, {scored_data: score})\n\n\n\n\n count += 1\n return count\n\n\n\n\nclass WebSocket_Handle(tornado.websocket.WebSocketHandler):\n\n def open(self):\n print(\"Web Socket is open\")\n # Read data from a sub system at regular intervals\n dataOut = {\"try this\":1}\n # Because the connection was just activated write out the data to the\n # websocket connected to a client\n self.write_message(json.dumps(dataOut))\n # setup a future call back of this routine so that data can be\n # refreshed on the client side\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(microseconds = WEBSOCKET_REFRESH_RATE_MS * 1000),\n self.update)\n\n # Open connection to redis here and store the handle as a property of this class\n self.rh = redis.Redis(host=REDIS_IP_ADDRESS, port=6379, db=0)\n self.ps = self.rh.pubsub()\n print(\"REDIS is open :)\")\n self.count = 0\n\n\n\n # Set this flag so that the websocket can be inform of its closing\n # if this in't done the socket might try transmitting on a close\n # connection and cause an error\n self.open = True\n\n def on_close(self):\n # Tell the possible future call back to update that the connection is\n # been closed. If not done will result in errors.\n self.open = False\n\n def on_message(self, message):\n # Recieve messages from the client here\n data = json.loads(message)\n # Print it to standard out after converting it from a string to a object\n applog(data)\n if \"obj_type\" in data and data['obj_type'] == 'UPDATE':\n self.count = add_interaction_to_redis(self.rh, data, self.count)\n else:\n applog(\"WARNING: Message in MBOC_ExecutionAction_Handler not expected> %s\\n\" % message)\n \n def update(self):\n # Read data from a sub system at regular intervals\n dataOut = {\"try this\":1}\n\n if self.open:\n # If the connection is still active write out the data to the\n # websocket connected to a client\n self.write_message(json.dumps(dataOut))\n # setup a future call back of this routine so that data can be\n # refreshed on the client side\n tornado.ioloop.IOLoop.instance().add_timeout(\n datetime.timedelta(microseconds = WEBSOCKET_REFRESH_RATE_MS * 1000),\n self.update)\n\n# ******************************************************************************\n# ******************************************************************************\n# Web Page Handler\n\nclass Main_Page_Handler(BaseHandler):\n def get(self):\n # Hand back from a get request with no fancy stuff\n self.render(\"index.html\")\n\nclass NotFoundHandler(tornado.web.RequestHandler):\n def prepare(self): # for all methods\n raise tornado.web.HTTPError(\n status_code=404,\n reason=\"Invalid resource path.\"\n )\n self.render(\"./public/404.html\")\n\n\ndef prefix_with_base(url):\n if url:\n composed = \"{0}/{1}\".format(BASE_PATH, url)\n else:\n composed = BASE_PATH or \"/\"\n applog('Composed URL: ' + composed)\n return composed\n\np = prefix_with_base\n\n# *** Settings, app setup and execution\nsettings = {\n \"template_path\": './public',\n \"static_path\":'./public',\n \"debug\":True,\n \"cookie_secret\": \"A secret shared is not a secret\",\n \"login_url\": \"/auth/login/\",\n \"default_handler_class\": NotFoundHandler\n}\n\napplication = tornado.web.Application([\n #\n # Get Main Page\n (p(''), Main_Page_Handler),\n #\n # Websocket handlers\n (p('services/ws'),WebSocket_Handle),\n #\n # Anything not handled above and static in nature (in a file) handled here\n (r\"/(.*)\", tornado.web.StaticFileHandler, {\"path\": \"./public\", \"default_filename\": \"index.html\"})\n ], **settings)\n\n\nif __name__ == \"__main__\":\n # Start it all up\n\n application.listen(WEB_SITE_PORT)\n tornado.ioloop.IOLoop.current().start()\n","sub_path":"FrontEnd/src/web-start.py","file_name":"web-start.py","file_ext":"py","file_size_in_byte":7496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"240739781","text":"#find how many pairs of numbers are there in a given array divisible by x. Print those pairs\ndef findDivisibleSumPairs(arr,x):\n bigArr = []\n count = 0\n for i in range(len(arr)-1):\n for j in range(i+1,len(arr)):\n if((arr[i] + arr[j]) % x == 0):\n bigArr.append([arr[i],arr[j]])\n count += 1\n return(bigArr,count)\n\narr = list(map(int,input(\"Please enter the space separated list for divisible sum pairs \").strip().split()))\nx = int(input(\"Please enter the number to be tested for divisibility \"))\n( bigArr, count ) = findDivisibleSumPairs(arr,x)\nprint(bigArr)\nprint(count)","sub_path":"level2/divisibleSumPairs.py","file_name":"divisibleSumPairs.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"532453291","text":"#!/usr/bin/python2.7\nimport tensorflow as tf\nimport keras\nfrom keras.backend.tensorflow_backend import set_session\nimport os\ngpu=6\nif(gpu!=-1):\n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=str(gpu)\n config =tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction=0.3\n\n set_session(tf.Session(config=config))\nwith tf.Session() as sess:\n devices = sess.list_devices()\n print(devices)\n\n\nprint(\"ernd\")\n","sub_path":"tfgpu.py","file_name":"tfgpu.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"108850705","text":"'''\nCreated on Oct 25, 2015\n\n@author: siva\n'''\nimport game_config\nimport MCS_Node\nimport MCS_support\nimport copy\nimport time\nimport random\nimport math\n\nrandom.seed()\ntime_limit_s = 10\n\nprint ('Hello World')\ngame_root = MCS_Node.MCTSnode(None,game_config.INIT_GAMESTATE,'tree_root')\ncurr_board = MCS_support.Game_board(game_root.node_gamestate)\nprint('Initial Game state')\ngame_root.print_gamestate()\nprint('***************************************************')\nprint('Terminal game states:')\nprint('*********************')\ngame_solved_flag = False\ngame_node_count = 0\nstart = time.time()\nbest_effort = math.floor(math.pow(game_config.GAME_DIMENSION, 4) )\nbest_effort_gamestate = copy.deepcopy(game_config.INIT_GAMESTATE)\ncurr_gamestate = copy.deepcopy(game_config.INIT_GAMESTATE)\nwhile(1):\n empty_row_idx = copy.deepcopy(curr_board.min_choice_row)\n empty_col_idx = copy.deepcopy(curr_board.min_choice_col) \n '''print('Selected location:',empty_row_idx,empty_col_idx)'''\n possible_vals = curr_board.board_cells[empty_row_idx][empty_col_idx].cell_choices\n '''print('Possible_vals:',possible_vals)'''\n if possible_vals != []:\n nxt_choice = random.choice(possible_vals)\n '''print('Nxt choice:',nxt_choice)'''\n curr_gamestate[empty_row_idx][empty_col_idx] = nxt_choice\n '''for cntr_row in range(game_config.GAME_DIMENSION * game_config.GAME_DIMENSION):\n print(curr_gamestate[cntr_row])'''\n curr_board = MCS_support.Game_board(curr_gamestate)\n zero_count = 0\n for i in range(game_config.GAME_DIMENSION * game_config.GAME_DIMENSION):\n zero_count = zero_count + curr_gamestate[i].count(0)\n if(zero_count < best_effort):\n best_effort = copy.deepcopy(zero_count)\n best_effort_gamestate = copy.deepcopy(curr_gamestate)\n if (zero_count == 0):\n end= time.time();\n print('Solved:')\n for cntr_row in range(game_config.GAME_DIMENSION * game_config.GAME_DIMENSION):\n print(curr_gamestate[cntr_row])\n print(abs(end - start))\n break\n elif(time.time() > (start + time_limit_s)):\n print('Time over:Unfilled:',best_effort)\n for cntr_row in range(game_config.GAME_DIMENSION * game_config.GAME_DIMENSION):\n print(best_effort_gamestate[cntr_row])\n break\n else:\n curr_gamestate = copy.deepcopy(game_config.INIT_GAMESTATE)\n curr_board = MCS_support.Game_board(game_root.node_gamestate) ","sub_path":"Solve_IS_guided.py","file_name":"Solve_IS_guided.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"432769853","text":"# NP完全问题\n# 全排列问题\n# 生成排序 ->计算路程 ->评价 ->选择 ->遗传 ->\n\n\nimport numpy as np\nfrom numpy import sum as npsum\nfrom numpy import append as npappend\nfrom numpy.random import randint as nprandint\nimport random\nfrom matplotlib import pyplot as plt\nfrom numba import jit\nimport time\nimport json\n# 导入数据集\nfrom data import city2, city3, city4, city5, city6\n\n\n# 参数设置\ncity = city4 # 默认城市数据集\npPopu = 0.0001 # 初始化种群个体数占总可能的比例\npAban = 0.45 # 样本总体中舍弃个体比例\npVari = 0.35 # 群体变异比例\npCloneWithVari = 0.05 # 优质个体直接变异产生新个体比例\npResrve = 0.01 # 样本总体中保留个体比例\nnMax = 3000 # 最大个体数\n\n\n# 样本种群数量\nsize = len(city) # 城市数量\nnPopu = round(np.math.factorial(size)*pPopu)\nif(nMax < nPopu):\n nPopu = nMax # 样本总数\n\n\n# 内部数据矩阵、向量初始化 (预分配空间不足时修改此处)\nmInterval = np.zeros([size, size]) # 城市间距矩阵\nmRoute = np.zeros([size, nPopu]).astype(np.int) # 路线矩阵\n# mCross = np.zeros([size, round(nPopu*0.5)]).astype(np.int) # 待交叉备份矩阵\n# mVari = np.zeros([size, round(nPopu*0.5)]).astype(np.int) # 待变异备份矩阵\nmConbine = np.zeros([size*2, round(nPopu*0.5)]).astype(np.int) # 交叉准备矩阵\naDistance = np.zeros(nPopu) # 距离向量\naResr = np.zeros(round(nPopu*0.05)).astype(np.int) # 选择保留个体\naAban = np.zeros(round(nPopu*0.5)).astype(np.int) # abandon 舍弃个体编号\naVari = np.zeros(round(nPopu*0.5)).astype(np.int) # variation 变异个体编号\naCloneWithVari = np.zeros(round(nPopu*0.1)).astype(np.int) # 直接变成新个体编号\naCross = np.zeros(round(nPopu*0.5)).astype(np.int) # Cross 交叉个体编号\naNext = np.zeros(nPopu).astype(np.int) # 下一轮需要更新距离个体(本轮已调整个体)\n# aNext初始化\naNext = np.arange(nPopu) # 对于初始轮所有个体均需要更新\n\n\n# 规模初始化\ndef scaleInitialization():\n global nAban, nResr, nCross, nVari, nCloneWithVari # , nNext\n nAban = np.floor(nPopu*pAban).astype(np.int) # 舍弃个体总数\n nResr = np.floor(nPopu*pResrve).astype(np.int) # 保留个体总数\n nVari = np.floor(nPopu*pVari).astype(np.int) # 变异个体总数\n # 优质个体直接变异产生新个体数\n nCloneWithVari = (np.floor(nPopu*pCloneWithVari).astype(np.int))//2*2\n nCross = nAban-nCloneWithVari # 交叉个体总数\n # nNext = nAban + nVari # 下一轮调整个数\n\n\n# 初始化城市间隔矩阵\ndef intervalInitialization(dataImport=0, input=False):\n global mInterval\n if input:\n mInterval = dataImport\n else:\n for ii in range(size):\n mInterval[:, ii] = np.sqrt(np.sum(np.square(city[ii, :]-city), 1))\n\n\n# 初始化种群\ndef populationInitialization():\n global mRoute\n for ii in range(nPopu):\n mRoute[:, ii] = np.random.permutation(size)\n\n\n# 计算路线路程\ndef distanceUpdate(nNext):\n global aDistance\n wayRoll = np.zeros(size).astype(np.int)\n for ii in range(nNext):\n way = mRoute[:, aNext[ii]]\n wayRoll[0] = way[-1]\n wayRoll[1:] = way[0:size-1]\n aDistance[aNext[ii]] = npsum(mInterval[way, wayRoll])\n\n\n# 规模更新\ndef scaleUpdate(prev, step, direction):\n global nAban, nResr, nCross, nVari, nCloneWithVari # , nNext\n # 方案一(迟滞反馈)\n # 主要作用在于后期精细化搜索\n # if (step < 0.00001):\n # direction -= 1\n # if (direction == 0):\n # scaleInitialization()\n # if (-2 < direction) and (direction <= 0):\n # # if (-2 < direction):\n # nAban = np.round(nAban*0.49).astype(np.int)*2\n # nCross = nAban - nCloneWithVari\n # nVari = np.floor(nVari*1.02).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n # # nNext = nAban + nVari\n # # 主要作用在于前期加速搜索\n # elif (step > 0.005*prev):\n # direction += 1\n # if (direction == 0):\n # scaleInitialization()\n # if (0 <= direction) and (direction < 2):\n # # if (direction < 2):\n # nAban = np.round(nAban*0.51).astype(np.int)*2\n # nCross = nAban - nCloneWithVari\n # nVari = np.floor(nVari*0.98).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n # # nNext = nAban + nVari\n\n # 方案二(实时反馈)\n change = False\n if (-2 < direction) and (step < 0.00001):\n direction -= 1\n change = True\n elif (direction < 2) and (step > 0.003*prev):\n direction = 2\n change = True\n\n if change:\n # scaleInitialization()\n if (direction == -1):\n nAban = np.round(nPopu*pAban*0.49).astype(np.int)*2\n nCross = nAban - nCloneWithVari\n nVari = np.floor(nPopu*pVari*1.02).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n elif (direction == -2):\n nAban = np.round(nPopu*pAban*0.48).astype(np.int)*2\n nCross = nAban - nCloneWithVari\n nVari = np.floor(nPopu*pVari*1.04).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n elif (direction == 1):\n nAban = np.round(nPopu*pAban*0.51).astype(np.int)*2\n nCross = nAban - nCloneWithVari\n nVari = np.floor(nPopu*pVari*0.98).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n elif (direction == 2):\n nAban = np.round(nPopu*pAban*0.52).astype(np.int)*2\n nCross = nAban - nCloneWithVari\n nVari = np.floor(nPopu*pVari*0.96).astype(np.int)\n # nCloneWithVari = ((nPopu*pCloneWithVari).astype(np.int))//2*2\n\n return direction\n\n\n\n\n# 适应度评价\ndef fitness():\n global aAban, aVari, aCross, aCloneWithVari, aResr, aNext\n rank = aDistance.argsort()\n aAban[0:nAban] = np.array(random.sample(\n list(rank[-(1.8*nAban).astype(np.int):]), nAban))\n aResr[0:nResr] = rank[0:nResr]\n aCross[0:10*nResr] = rank[0:20*nResr:2]\n aCross[10*nResr:nCross\n ] = random.sample(list(rank[20*nResr:]), nCross-10*nResr)\n np.random.shuffle(aCross[0:nCross])\n aCloneWithVari[0:nCloneWithVari] = rank[0:nCloneWithVari]\n rank = np.array(list(set(rank)-set(aResr[0:nResr])-set(aAban[0:nAban])))\n aVari[0:5*nResr] = rank[np.arange(0, 5*nResr)*2]\n aVari[5*nResr:nVari\n ] = random.sample(list(rank[10*nResr:]), nVari-5*nResr)\n # np.random.shuffle(aVari[0:nVari])\n # aNext[0:nNext] = npappend(aAban[0:nAban], aVari[0:nVari])\n aNext[0:nAban] = aAban[0:nAban]\n aNext[nAban:nAban+nVari] = aVari[0:nVari]\n\n\n# 变异、交叉、遗传\n# @profile\ndef heredity():\n global mRoute, mConbine\n # Cross 方案一(交叉位置交叉法)\n # for ii in range(nCross//2):\n # fGene = np.zeros(size*2).astype(np.int)\n # cGene0 = list()\n # cGene1 = list()\n # for ij in range(size):\n # fGene[[ij*2, ij*2+1]] = [mRoute[:, aCross[ii]][ij],\n # mRoute[:, aCross[ii+nCross//2]][ij]]\n # for item in fGene:\n # if (not item in cGene0):\n # cGene0.append(item)\n # else:\n # cGene1.append(item)\n # mRoute[:, aAban[ii*2]] = cGene0\n # mRoute[:, aAban[ii*2+1]] = cGene1\n\n # Cross 方案二(基于运行效率考虑,交叉原理同方案一)\n # 备份待交叉个体,防止被下一步操作影响(部分个体同时存在于待交叉与待舍弃行列)\n # mCross[:, 0:nCross] = mRoute[:, aCross[0:nCross]]\n # # 对所有即将被交叉替代路线操作,路线值为负,方便后续查找\n # mRoute[:, aAban[0:nCross]] -= size\n # for ii in range(nCross//2):\n # # 数组指针\n # ptr0 = ptr1 = 0\n # for ij in range(size):\n # # 第一个父代个体\n # if (mCross[:, ii][ij] in mRoute[:, aAban[ii*2]]):\n # mRoute[:, aAban[ii*2+1]][ptr1] = mCross[:, ii][ij]\n # ptr1 += 1\n # else:\n # mRoute[:, aAban[ii*2]][ptr0] = mCross[:, ii][ij]\n # ptr0 += 1\n # # 第二个父代个体\n # if (mCross[:, ii+nCross//2][ij] in mRoute[:, aAban[ii*2]]):\n # # 存在边界问题\n # mRoute[:, aAban[ii*2+1]][ptr1] = mCross[:, ii+nCross//2][ij]\n # ptr1 += 1\n # else:\n # mRoute[:, aAban[ii*2]][ptr0] = mCross[:, ii+nCross//2][ij]\n # ptr0 += 1\n\n # 方案三(高效 不同于方案一、方案二 直接交叉 去重补缺)\n # 点位选取\n position = np.random.randint(0, size, nCross//2)\n # 程度(交叉位置数)\n level = np.random.randint(1, size, nCross//2)\n # 交叉位置索引\n crossArea = np.array([np.arange(x, x+y) %\n size for x, y in zip(position, level)])\n # 带交叉父代基因合并\n mConbine[0:size, 0:nCross//2] = mRoute[:, aCross[0:nCross//2]]\n mConbine[size:size*2, 0:nCross//2] = mRoute[:, aCross[nCross//2:nCross]]\n entirety = np.arange(size*2)\n for ii in range(nCross//2):\n mConbine[[npappend(crossArea[ii], crossArea[ii]+size)],\n ii] = mConbine[[npappend(crossArea[ii]+size, crossArea[ii])], ii]\n # 找出未重复的一组路线\n _, index = np.unique(mConbine[:, ii], return_index=True)\n mRoute[:, aAban[ii*2]] = mConbine[:, ii][np.sort(index)]\n # 剩下的一组路线\n # indexLeft = entirety[np.isin(entirety, index, invert=True)]\n indexLeft = np.array(list(set(entirety)-set(index)))\n mRoute[:, aAban[ii*2+1]] = mConbine[:, ii][np.sort(indexLeft)]\n\n # # Variation\n # # 优质个体直接变异替代被舍弃个体\n # # 变异\n # # # 点位选取\n # position0 = np.random.randint(0, size, nCloneWithVari)\n # # 变异程度(移动位置数)\n # level = np.random.randint(1, size//3, nCloneWithVari)\n # position1 = np.array([nprandint(x+y, x+size-y) %\n # size for x, y in zip(position0, level)])\n # posSwap = np.array([(np.arange(x, x+y) % size, np.arange(y, y+z) % size)\n # for x, y, z in zip(position0, position1, level)])\n # mRoute[:, aAban[nCross:nCross+nCloneWithVari]\n # ] = mRoute[:, aCloneWithVari[0:nCloneWithVari]]\n # for ii in range(nCloneWithVari):\n # mRoute[:, aAban[ii+nCross]][(npappend(posSwap[ii][0], posSwap[ii][1]))\n # ] = mRoute[:, aAban[ii+nCross]][(npappend(posSwap[ii][0], posSwap[ii][1]))]\n\n # # 方法二(所有新个体与原个体均不同,相比方法一收敛减慢)\n # 点位选取\n position = np.random.randint(0, size, nCloneWithVari)\n # 变异程度(移动位置数)\n level = np.random.randint(1, size, nCloneWithVari)\n posInsert = np.array([nprandint(0, size-x) for x in level])\n for ii in range(nCloneWithVari):\n # 选中位移的位置\n posSelect = np.arange(position[ii], position[ii]+level[ii]) % size\n # 剩余位置向量\n posLeft = np.arange(position[ii]+level[ii], position[ii]+size) % size\n #\n mRoute[:, aAban[ii+nCross]][0:posInsert[ii]\n ] = mRoute[:, aCloneWithVari[ii]][posLeft[0:posInsert[ii]]]\n\n mRoute[:, aAban[ii+nCross]][posInsert[ii]:posInsert[ii] + level[ii]\n ] = mRoute[:, aCloneWithVari[ii]][posSelect]\n\n mRoute[:, aAban[ii+nCross]][posInsert[ii]+level[ii]:\n ] = mRoute[:, aCloneWithVari[ii]][posLeft[posInsert[ii]:]]\n\n # 变异\n # 点位选取\n position0 = np.random.randint(0, size, nVari)\n # 变异程度(移动位置数)\n level = np.random.randint(1, 5, nVari)\n position1 = np.array([nprandint(x+y, x+size-y) %\n size for x, y in zip(position0, level)])\n posSwap = np.array([(np.arange(x, x+y) % size, np.arange(y, y+z) % size)\n for x, y, z in zip(position0, position1, level)])\n # mVari[:, 0:nVari] = mRoute[:, aVari[0:nVari]]\n for ii in range(nVari):\n mRoute[:, aVari[ii]][(npappend(posSwap[ii][0], posSwap[ii][1]))\n ] = mRoute[:, aVari[ii]][(npappend(posSwap[ii][0], posSwap[ii][1]))]\n\n\n# plot\ndef plot():\n plt.plot(city[:, 0], city[:, 1], 'ro')\n index = mRoute[:, aDistance.argmin()]\n plt.plot(city[npappend(index, index[0]), 0],\n city[npappend(index, index[0]), 1])\n\n\n# data output\ndef write(usedTime, count):\n data = [size, count, np.min(aDistance), usedTime,\n mRoute[:, aDistance.argmin()].tolist()]\n with open(\"route.json\", 'a', encoding='utf-8') as output:\n json.dump(dict(zip(('number of city:', 'generation:', 'optimal distance:',\n 'used time(s)', 'route:'), data)), output, indent=4, ensure_ascii=False)\n print(\"All done!\")\n\n\ndef main():\n t0 = time.process_time()\n # 首次全体均需重新计算distance\n populationInitialization()\n intervalInitialization()\n scaleInitialization()\n distanceUpdate(nPopu)\n # 当前最优(current optimal)\n cp = np.min(aDistance)\n # run = True\n gene = 0\n thresholdValue = 0\n direction = 0\n print(\"{g:<10}{cp:<26}{jc:<26}\".format(\n g='gene', cp='Current optimal', jc='Judgment condition'))\n\n while(3*size >= thresholdValue):\n gene += 1\n prev = cp\n fitness()\n heredity()\n distanceUpdate(nAban+nVari)\n jc = np.average(np.sort(aDistance)[4*nResr:7*nResr])\n cp = np.min(aDistance)\n # 最优结果步进\n step = prev - cp\n # 判决门限\n if (not step):\n thresholdValue += 1\n else:\n thresholdValue = 0\n direction = scaleUpdate(prev, step, direction)\n print(\"{0:<9}\".format(gene), \"{0:<25}\".format(\n cp), \"{0:<25}\".format(jc))\n print(mRoute[:, aDistance.argmin()])\n\n usedTime = time.process_time()-t0\n\n # 结果输出\n write(usedTime, gene)\n\n\nif __name__ == \"__main__\":\n t0 = time.process_time()\n main()\n print(time.process_time()-t0)\n plot()\n plt.show()\n","sub_path":"GA/tsp-ga.py","file_name":"tsp-ga.py","file_ext":"py","file_size_in_byte":14461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"432684806","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 10 09:14:34 2019\n\n@author: DYYang\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 10 16:10:39 2019\n\n@author: DYYang\n\"\"\"\nimport csv\nimport os\nimport json\nimport xlrd\nfrom pypinyin import pinyin, lazy_pinyin\n\ndef loadFont(filename):\n if(os.path.exists(filename)==False):\n return \"False\";\n f = open(filename, encoding=\"utf-8\") #设置以utf-8解码模式读取文件,encoding参数必须设置,否则默认以gbk模式读取文件,当文件中包含中文时,会报错\n setting = json.load(f)\n #family = setting['BaseSettings']['size'] #注���多重结构的读取语法\n #size = setting['fontSize'] \n return setting;\n\n#读取xlsx表\ndata = xlrd.open_workbook('china_swine_flu_v8.xlsx')\n\nbreak_num={}\nfirst_break={}\nfirst_break_date={}\n#table = data.sheet_by_name(u'猪瘟爆发时间表')#通过名称获取\ntable = data.sheets()[0]\n\nids=table.col_values(0)\nbreak_date=table.col_values(1)\nprovince=table.col_values(4)\n\n#num_range=[1,4,7,11,21,30]\nnum_range=[20180800,20180900,20181000,20181100,20181200,20190200]\n\ntemp_colume=0\nfor pro in province:\n if(temp_colume==0):\n temp_colume+=1\n continue\n if(pro in break_num):\n break_num[pro]+=1\n else:\n break_num[pro]=1\n temp_date=break_date[temp_colume].split(\"年\")\n temp_year=temp_date[0]\n temp_str=temp_date[1].split(\"月\")\n temp_month=temp_str[0]\n temp_day=temp_str[1].split(\"日\")[0]\n if(len(temp_month)==1):\n temp_month=\"0\"+temp_month\n if(len(temp_day)==1):\n temp_day=\"0\"+temp_day\n first_break[pro]=int(temp_year+temp_month+temp_day)\n first_break_date[pro]=temp_year+\".\"+temp_month+\".\"+temp_day\n temp_colume+=1\n\n\nchina_data=loadFont(\"china_countries.json\")\ncountry_id=0\n\nfor country in china_data[\"features\"]:\n temp_name=country[\"properties\"][\"name\"]\n if(temp_name[0]=='黑' or temp_name[0]=='内'):\n temp_name=temp_name[0]+temp_name[1]+temp_name[2]\n else:\n temp_name=temp_name[0]+temp_name[1]\n china_data[\"features\"][country_id][\"properties\"][\"chinese_name\"]=temp_name\n name_loc=-1 \n china_data[\"features\"][country_id][\"properties\"][\"name\"]=''.join(lazy_pinyin(temp_name)).capitalize()\n if(temp_name in break_num):\n china_data[\"features\"][country_id][\"properties\"][\"main_data\"]=first_break[temp_name]\n china_data[\"features\"][country_id][\"properties\"][\"hasData\"]=1\n for i in range(len(num_range)-1):\n if(first_break[temp_name]>=num_range[i] and first_break[temp_name] SpectrumType:\n \"\"\"Find missing InchiKey and derive from Inchi where possible.\"\"\"\n\n spectrum = spectrum_in.clone()\n\n if has_valid_inchi(spectrum) and not has_valid_inchikey(spectrum):\n inchi = spectrum.get(\"inchi\")\n inchikey = mol_converter(inchi, \"inchi\", \"inchikey\")\n if not inchikey:\n print(\"Could not convert InChI\", inchi, \"to inchikey.\")\n inchikey = 'n/a'\n spectrum.set(\"inchikey\", inchikey)\n\n return spectrum\n","sub_path":"matchms/filtering/derive_inchikey_from_inchi.py","file_name":"derive_inchikey_from_inchi.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"228710216","text":"import random\nimport os\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nurl = 'https://movie.douban.com/subject/24753810/reviews?start=0'\n\nheaders = {\n\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'\n}\n\n\ndef get_html(url):\n try:\n res = requests.get(url, headers=headers)\n res.raise_for_status()\n res.encoding = 'utf-8'\n # print(res.text)\n return res.text\n except:\n print('get HTML failed')\n\n\ndef parse_html(html):\n soup = BeautifulSoup(html, 'lxml')\n reviews_div = soup.find('div', class_='review-list')\n # print(reviews_div)\n reviewer_name_info = reviews_div.find_all('a', class_='name')\n reviewer_name = [item.string for item in reviewer_name_info]\n # print(reviewer_name)\n\n reviews_title = [item.string for item in reviews_div.find_all('h2')]\n # print(reviews_title)\n full_reviews_url_a = [item.find('a') for item in reviews_div.find_all('h2')]\n full_reviews_url = [item.get('href') for item in full_reviews_url_a]\n # print(full_reviews_url)\n\n reviewer_info = reviews_div.find_all('a', class_='avator')\n reviewer_url = [item.get('href') for item in reviewer_info]\n reviewer_icon_list = [item.find('img') for item in reviewer_info]\n reviewer_img_url = [item.get('src') for item in reviewer_icon_list]\n # print(reviewer_img_url)\n\n reviews_date_span = reviews_div.find_all('span', property='v:dtreviewed')\n reviews_date = [item.string for item in reviews_date_span]\n # print(reviews_date)\n\n reviews_div_list = reviews_div.find_all('div', class_='short-content')\n # reviews_list = []\n # for item in reviews_div_list:\n # item = item.stripped_strings\n # for i in item:\n # reviews_list.append(i)\n reviews_list = [item.get_text() for item in reviews_div_list]\n reviews_list = [item.strip() for item in reviews_list]\n # print(reviews_list[0])\n\n return reviewer_name, reviewer_url, reviewer_img_url, reviews_date, reviews_title, reviews_list, full_reviews_url\n\n\nif __name__ == '__main__':\n for i in range(1, 1000, 19):\n url = 'https://movie.douban.com/subject/24753810/reviews?start={}'.format(i)\n html = get_html(url)\n reviewer_name, reviewer_url, reviewer_img_url, reviews_date, reviews_title, reviews_list, full_reviews_url = parse_html(\n html)\n\n df = pd.DataFrame({\n\n 'reviewerName': reviewer_name,\n 'reviewerUrl': reviewer_url,\n 'reviewer_img_url': reviewer_img_url,\n 'reviews_date': reviews_date,\n 'reviews_title': reviews_title,\n 'reviews': reviews_list,\n 'full_reviews_url': full_reviews_url\n })\n if not os.path.isfile('Douban_zhanlang.csv'):\n df.to_csv('Douban_zhanlang.csv', index=False, mode='a', sep=',', encoding='utf-8-sig')\n else:\n df.to_csv('Douban_zhanlang.csv', index=False, header=False, mode='a')\n time.sleep(random.random())\n print('write to csv done')\n","sub_path":"web_spider/douban_zhanlang.py","file_name":"douban_zhanlang.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"537591803","text":"#!/usr/bin/python3\n\"\"\" Export to CSV \"\"\"\nimport csv\nimport requests\nfrom sys import argv\n\nif __name__ == \"__main__\":\n url = 'https://jsonplaceholder.typicode.com'\n USER_ID = argv[1]\n \"\"\" Extract Employee name \"\"\"\n user = requests.get('{}/users/{}'.format(url, USER_ID)).json()\n USERNAME = user.get('username')\n \"\"\" Extract Employee Tasks \"\"\"\n todos = requests.get('{}/todos?userId={}'.format(url, USER_ID)).json()\n rows = []\n for Task in todos:\n TASK_COMPLETED_STATUS = Task.get(\"completed\")\n TASK_TITLE = Task.get(\"title\")\n rows.append([USER_ID, USERNAME, TASK_COMPLETED_STATUS, TASK_TITLE])\n filename = \"%s.csv\" % USER_ID\n \"\"\" export to csv file \"\"\"\n with open(filename, 'wt') as f:\n csv_writer = csv.writer(f, quoting=csv.QUOTE_ALL)\n [csv_writer.writerow(row) for row in rows]","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"473094006","text":"from django.core.paginator import Paginator\n\nmonths = {\n 'January': 'Enero',\n 'February': 'Febrero',\n 'March': 'Marzo',\n 'April': 'Abril',\n 'May': 'Mayo',\n 'June': 'Junio',\n 'July': 'Julio',\n 'August': 'Agosto',\n 'September': 'Septiembre',\n 'October': 'Octubre',\n 'November': 'Noviembre',\n 'December': 'Diciembre' \n }\n \ndef calc_page_range(page, num_pages):\n '''\n Calcular de qué página a qué página se mostrará el menu paginador.\n Ejemplo: si estas en la página 2, el paginador será de [2, 3, 4, 5, 6]\n '''\n start = page\n end = page + 4\n\n if end > num_pages:\n diff = end - num_pages\n end = end - diff\n\n page_range = [i for i in range(start, end+1)]\n\n return page_range\n\ndef pagination(objects, page):\n p = Paginator(objects, 10)\n\n if not page:\n page = 1\n\n page_range = calc_page_range(int(page), p.num_pages)\n\n return p, page, page_range\n\ndef locale_date(date):\n '''Funcion para dar formato humano (y en español) a las fechas.'''\n \n # obtener el mes en idioma español\n en_month = date.strftime('%B')\n es_month = months[en_month]\n\n # escribir fecha completa en forma de texto en español\n fecha = date.strftime('%d de {mes} del %Y, %H:%M %p').format(mes=es_month)\n\n return fecha ","sub_path":"inventario/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"272296676","text":"class Solution:\n def kSum(self, A, k, target):\n n = len(A)\n dp = [\n [[0] * (target + 1) for _ in range(k + 1)], # 三维列表, [0]也是一个列表\n [[0] * (target + 1) for _ in range(k + 1)],\n ]\n #dp[i][j][s]\n dp[0][0][0] = 1\n for i in range(1, n + 1):\n dp[i % 2][0][0] = 1\n for j in range(1, min(k + 1, i + 1)): #前i个数里挑出j个数,和为s\n for s in range(1, target + 1):\n dp[i % 2][j][s] = dp[(i - 1) % 2][j][s] # 当前i - 1个数中就能找出j个数满足条件时\n if s >= A[i - 1]: # 当前i - 1个数找不出k个数, 那就找一个加上最后一个数满足target的值\n dp[i % 2][j][s] += dp[(i - 1) % 2][j - 1][s - A[i - 1]]\n return dp[n % 2][k][target]\n\n\n# 主函数\nif __name__ == '__main__':\n A = [1, 2, 3, 4]\n k = 2\n target = 5\n print(\"初始数组A:\", A)\n print(\"整数k和目标值target:\", k, target)\n solution = Solution()\n print(\"方案种类:\", solution.kSum(A, k, target))","sub_path":"Python算法指南/没看懂/45_k数之和_DP没看懂_难.py","file_name":"45_k数之和_DP没看懂_难.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"265924234","text":"nums = [2,4,1,3,5,6]\nk = 2\n\nclass Solution:\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n return sorted(nums)[::-1][k-1]\n\nif __name__ == '__main__':\n leetcode = Solution()\n print(leetcode.findKthLargest(nums, k))\n","sub_path":"215/sort_O_nlogn.py","file_name":"sort_O_nlogn.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"620676346","text":"#!/usr/bin/env python\n\nimport urllib.request\nimport json\nimport datetime\nimport pymysql\n\n# mysql db\nmysql_server = '10.48.192.162'\nmysql_username = 'lemon'\nmysql_password = 'memory'\nmysql_port = 3306\nmysql_db = 'Lemon_GO'\n\nrest_api_url = 'http://10.48.192.162:8888/server_info'\n\ntry:\n server_info_bytes = urllib.request.urlopen(rest_api_url)\n \nexcept urllib.error.HTTPError as e:\n print(e.code)\n print(e.read().decode(\"utf8\"))\n \nserver_info_string = server_info_bytes.read().decode('utf-8')\nserver_info_dict = json.loads(server_info_string)\n\n#for k,v in server_info_dict.items():\n# print(k,v)\n\ntry:\n conn = pymysql.connect(host=mysql_server, port=mysql_port, user=mysql_username, passwd=mysql_password,\n db=mysql_db, charset='utf8')\n curs = conn.cursor()\n for salt_minion_name in server_info_dict:\n server_hostname = server_info_dict[salt_minion_name]['nodename']\n server_ipaddr = server_info_dict[salt_minion_name]['ip4_interfaces:eth0'][0]\n server_os = server_info_dict[salt_minion_name]['os'] + '-' + server_info_dict[salt_minion_name]['osrelease'] + '-' + server_info_dict[salt_minion_name]['osarch']\n server_cpu = str(server_info_dict[salt_minion_name]['num_cpus']) + ' * ' + server_info_dict[salt_minion_name]['cpu_model'] \n server_memory = server_info_dict[salt_minion_name]['mem_total']\n server_model = server_info_dict[salt_minion_name]['virtual']\n created_time = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')\n print(server_hostname,server_ipaddr,server_os,server_cpu,created_time)\n\t\n\t# if records exists, update , hostname and ip must unique\n# curs.execute('''insert into server (server_hostname, server_ipaddr, server_os,\n# server_cpu, server_memory, server_model, created_time)\n# VALUES( '%(server_hostname)s', '%(server_ipaddr)s', '%(server_os)s', '%(server_cpu)s', '%(server_memory)s',\n# '%(server_model)s', '%(created_time)s')\n# on duplicate key update server_cpu='%(server_cpu)s', server_memory='%(server_memory)s' ''' % {\n# 'server_hostname':server_hostname, 'server_ipaddr':server_ipaddr, 'server_os':server_os,'server_cpu':server_cpu,\n# 'server_memory':server_memory, 'server_model':server_model, 'created_time': created_time })\n curs.execute('''replace into server (server_hostname, server_ipaddr, server_os,\n server_cpu, server_memory, server_model, created_time)\n VALUES( '%(server_hostname)s', '%(server_ipaddr)s', '%(server_os)s', '%(server_cpu)s', '%(server_memory)s',\n '%(server_model)s', '%(created_time)s') ''' % {\n 'server_hostname':server_hostname, 'server_ipaddr':server_ipaddr, 'server_os':server_os,'server_cpu':server_cpu,\n 'server_memory':server_memory, 'server_model':server_model, 'created_time': created_time })\n data = curs.fetchall()\n \n if len(data) is 0:\n conn.commit()\n print('Insert record OK')\n\nexcept Exception as e:\n print(str(e))\n \nfinally:\n curs.close()\n conn.close()\n","sub_path":"Script/auto_add_server_info.py","file_name":"auto_add_server_info.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"157230350","text":"print('----- Data execution initialized -----')\n\nfrom facebookads import adobjects\nfrom facebookads.api import FacebookSession\nfrom facebookads.api import FacebookAdsApi\nfrom facebookads.adobjects.adaccountuser import AdAccountUser\nfrom facebookads.adobjects.adaccount import AdAccount\nfrom facebookads.adobjects.user import User\nfrom facebookads.adobjects.campaign import Campaign\n\nimport json\nimport pandas as pd\nimport json\nimport os\n\n\ndef facebook_get_service(config):\n '''\n Connects to Facebook Ads platform\n '''\n session = FacebookSession(\n config['app_id'],\n config['app_secret'],\n config['access_token']\n )\n api = FacebookAdsApi(session)\n FacebookAdsApi.set_default_api(api)\n FacebookAdsApi.init(\n config['app_id'],\n config['app_secret'],\n config['access_token']\n )\n\n\ndef facebook_data_extraction(config):\n '''\n Facebook Ads platform data extraction\n '''\n facebook_get_service(config)\n me = User(fbid='me')\n print('me', me)\n print(\n 'me.remote_read(fields=[User.Field.permissions])',\n me.remote_read()\n )\n ad_account = AdAccount(config['ad_account_id'])\n print('ad_account', ad_account.remote_read())\n print('ad_account', ad_account.get_campaigns())\n return ''\n\n\ndef youtube_data_extraction():\n return ''\n\n\ndef instagram_data_extraction():\n return ''\n\n\ndef analytics_data_extraction():\n return ''\n\n\ndef extract(config):\n '''\n Returns tupple of data of sources, respectively:\n - YT\n - GA\n - FB\n - Inst\n '''\n fb_data = facebook_data_extraction(config['facebook'])\n yt_data = youtube_data_extraction()\n ga_data = youtube_data_extraction()\n inst_data = youtube_data_extraction()\n return yt_data, ga_data, fb_data, inst_data\n\n\ndef youtube_data_transform(yt_data):\n '''\n Returns formatted df of YT data\n '''\n result = yt_data\n return result\n\n\ndef facebook_data_transform(fb_data):\n '''\n Returns formatted df of FB data\n '''\n result = fb_data\n return result\n\n\ndef analytics_data_transform(ga_data):\n '''\n Returns formatted df of FB data\n '''\n result = ga_data\n return result\n\n\ndef instagram_data_transform(inst_data):\n '''\n Returns formatted df of Inst data\n '''\n result = inst_data\n return result\n\n\ndef transform(data):\n '''\n Transforms and formats data into Pandas dataFrame\n\n Returns tuple of sources: \n - YT\n - GA\n - FB\n - Inst\n '''\n yt_formatted_data = youtube_data_transform(data[0])\n ga_formatted_data = analytics_data_transform(data[1])\n fb_formatted_data = facebook_data_transform(data[2])\n inst_formatted_data = instagram_data_transform(data[3])\n return (\n yt_formatted_data,\n ga_formatted_data,\n fb_formatted_data,\n inst_formatted_data\n )\n\n\ndef load(data):\n '''\n General data loading function\n '''\n return ''\n\n\ndef main():\n '''\n General marketing data ETL script for New Content\\'s work for Electro Lux\n '''\n this_dir = os.path.dirname(__file__)\n config_filename = os.path.join(this_dir, 'config.json')\n config_file = open(config_filename)\n config = json.load(config_file)\n config_file.close()\n \n load(\n transform(\n extract(config)\n )\n )\n print('----- Data execution finished successfully -----')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"37775463","text":"import oyaml as yaml\nfrom scapy.all import *\nfrom scapy.layers.inet import IP, TCP\nimport sys\n\narp_tracker = {}\n\n# Takes in a packet, checks if that IP/ MAC Address has been previously mapped\ndef arp_cache_poisoning(pkt):\n if pkt.psrc in arp_tracker and pkt.hwsrc != arp_tracker[pkt.psrc]: # In ARP, the pkt.hwsrc is used to denote the address that was being looked for\n print_packet(pkt, \"arp_cache_poisoning\")\n elif pkt.psrc not in arp_tracker.keys():\n for ip in arp_tracker.keys():\n if arp_tracker[ip] == pkt.hwsrc:\n print_packet(pkt, \"arp_cache_poisoning\")\n arp_tracker[pkt.psrc]= pkt.hwsrc\n\ndef print_packet(pkt, attack_type: str):\n yaml_dump= {}\n yaml_dump['timestamp']= int(pkt.time)\n yaml_dump['source']= {'mac_address': pkt.hwsrc, 'ipv4_address': pkt.psrc, 'tcp_port': None}\n yaml_dump['target']= {'mac_address': pkt.hwdst, 'ipv4_address': pkt.pdst, 'tcp_port': None}\n yaml_dump['attack']= attack_type\n print(yaml.dump(yaml_dump)+'---')\n\ndef main():\n packets= rdpcap(sys.argv[1])\n print('Starting ARP cache poisoning detection\\n')\n for pkt in packets:\n if 'ARP' in pkt and pkt.op == 2: # Get only 'is-at' packets that are ARP protocol\n arp_cache_poisoning(pkt)\n print('Finished ARP cache poisoning detection\\n')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/arp_cache_poisoning.py","file_name":"arp_cache_poisoning.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"182050814","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\nimport datetime\nimport const\nimport pymongo\n\n\ndef configure_logger(logger=logging.getLogger('dw')):\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\n console_handler = logging.StreamHandler()\n console_handler.setLevel(const.CONSOLE_LOGLEVEL)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n\n\ndef query_for_overview():\n client = pymongo.MongoClient(\"mongodb://localhost:27017\")\n db = client.maps\n poznan = db.poznan\n\n logger.debug(\"Number of documents: %r\", poznan.find().count())\n logger.debug(\"Number of nodes: %r\", poznan.find({\"type\": \"node\"}).count())\n logger.debug(\"Number of ways: %r\", poznan.find({\"type\": \"way\"}).count())\n logger.debug(\"Number of distinct users: %r\", len(poznan.distinct(\"created.user\")))\n\n top3 = poznan.aggregate([\n {\"$group\": {\"_id\": \"$created.user\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}},\n {\"$limit\": 3}\n ])\n logger.debug(\"Top 3 contributing users: %r\", [i for i in top3])\n\n avg = poznan.aggregate([\n {\"$group\": {\"_id\": \"$created.user\", \"count\": {\"$sum\": 1}}},\n {\"$group\": {\"_id\": \"$created.user\", \"average\": {\"$avg\": \"$count\"}}}\n ])\n logger.debug(\"Average contributions per user: %r\", [i for i in avg])\n\n\ndef query_topten():\n client = pymongo.MongoClient(\"mongodb://localhost:27017\")\n db = client.maps\n poznan = db.poznan\n\n doccount = poznan.find().count()\n\n topten = list(poznan.aggregate([\n {\"$group\": {\"_id\": \"$created.user\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}},\n {\"$limit\": 10}\n ]))\n\n topcnt = topten[0].get(\"count\")\n logger.debug(\"Top user contributions: %r, %r\", topcnt, float(topcnt) / doccount * 100)\n\n top2cnt = topten[0].get(\"count\") + topten[1].get(\"count\")\n logger.debug(\"Top two users contributions: %r, %r\", top2cnt, float(top2cnt) / doccount * 100)\n\n toptencnt = 0\n for u in topten:\n toptencnt += u.get(\"count\")\n\n logger.debug(\"Top ten users contributions: %r, %r\", toptencnt, float(toptencnt) / doccount * 100)\n\n\ndef query_fuel():\n client = pymongo.MongoClient(\"mongodb://localhost:27017\")\n db = client.maps\n poznan = db.poznan\n\n res = poznan.aggregate([{\"$match\": {\"amenity\": \"fuel\"}},\n {\"$group\": {\"_id\": \"$operator\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}}, {\"$limit\": 3}])\n\n logger.debug(list(res))\n\n\ndef query_credit():\n client = pymongo.MongoClient(\"mongodb://localhost:27017\")\n db = client.maps\n poznan = db.poznan\n\n\n\n # res = poznan.aggregate([{\"$match\": {\"wheelchair\": \"yes\"}},\n # {\"$group\": {\"_id\": \"$name\", \"count\": {\"$sum\": 1}}},\n # {\"$sort\": {\"count\": -1}}, {\"$limit\": 10}])\n\n all_amenities = poznan.find({\"amenity\": {\"$exists\": \"true\"}}).count()\n wheelchair_accessible = poznan.find({\"amenity\": {\"$exists\": \"true\"}, \"wheelchair\": \"yes\"}).count()\n logger.debug(all_amenities)\n logger.debug(wheelchair_accessible)\n\n\nif __name__ == \"__main__\":\n start_time = datetime.datetime.now()\n logger = logging.getLogger(const.LOGGER_NAME)\n configure_logger(logger)\n logger.info('Script has started')\n\n # query_for_overview()\n # query_topten()\n # query_fuel()\n query_credit()\n\n logger.info('Script has finished running. Script ran: %s', datetime.datetime.now() - start_time)\n logger.info('-' * 80)\n","sub_path":"project/query_mongo.py","file_name":"query_mongo.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"203385331","text":"import re\nfrom additional import aaa, dot, space_insert\nfrom collections import Counter\n \n\ndef L_distance(a, b):\n l1 = {'ц' : 'cons','к' : 'cons','н' : 'cons','г' : 'cons','ш' : 'cons','щ' : 'cons','з' : 'cons','х' : 'cons','ф' : 'cons','в' : 'cons','п' : 'cons',\n 'р' : 'cons','л' : 'cons','д' : 'cons','ж' : 'cons','ч' : 'cons','с' : 'cons','м' : 'cons','т' : 'cons','б' : 'cons', 'у' : 'vow', 'е' : 'vow',\n 'ы' : 'vow', 'а' : 'vow', 'о' : 'vow', 'э' : 'vow', 'я' : 'vow', 'и' : 'vow', 'ю' : 'vow', 'ё' : 'vow', 'й' : 'vow', 'ъ' : 'vow', 'ь' : 'vow', '-' : 'dash'}\n l2 = ['ао', 'оа', 'еи', 'ие', 'еэ', 'эе', 'ьи', 'иь', 'иы', 'ыи', 'ъь', 'ьъ', 'кг', 'гк' 'шщ', 'щш', 'оё', 'ёо', 'ую', 'юу']\n n, m = len(a), len(b)\n if n > m:\n a, b = b, a\n n, m = m, n\n current_row = range(n+1)\n for i in range(1, m+1):\n previous_row, current_row = current_row, [i]+[0]*n\n for j in range(1,n+1):\n add, delete, change = previous_row[j]+1, current_row[j-1]+1, previous_row[j-1]\n if a[j-1] != b[i-1]:\n if l1[a[j-1]] != l1[b[i-1]]:\n change += 1.5\n else:\n if a[j-1] + b[i-1] in l2:\n change += 0.5\n else:\n change += 1\n current_row[j] = min(add, delete, change)\n return current_row[n]\n\ndef not_latin(mst):\n n = re.search('[A-z0-9]', mst)\n if n is None:\n return True\n else:\n return False\n\ndef find_neares(mst, ruscorpora):\n d = 1000\n out = []\n for word in ruscorpora:\n if len(mst) - sum((Counter(mst) & Counter(word)).values()) < 3:\n if not_latin(word):\n nd = L_distance(mst, word)\n if nd < d:\n d = nd\n out = [word]\n elif nd == d and word not in out:\n out.append(word)\n return out, d\n\ndef correction(mistake, abbrevs, neologismy, ruscorpora, matrix):\n mst = aaa(mistake)\n if mst not in ruscorpora and dot(mst):\n if mst not in abbrevs:\n if mst not in neologismy:\n if not_latin(mst):\n m = cut_the_corpus(mst, 'привоз', matrix)\n out = find_neares(mst, m)\n else:\n out = ([mst], 0)\n else:\n out = ([mst], 0)\n else:\n out = ([mst], 0)\n else:\n out = ([mst], 0)\n return out\n\ndef create_matrix(word, ruscorpora):\n matrix ={}\n for i in ruscorpora:\n if not_latin(i):\n nd = L_distance(i, word)\n if nd not in matrix:\n matrix[nd] = [i]\n else:\n matrix[nd].append(i)\n return matrix\n\ndef cut_the_corpus(word, mztrix_word, matrix):\n out = []\n l = L_distance(mztrix_word, word)\n cof = [l-1.5, l-1, l-0.5, l, l+0.5, l+1, l+1.5]\n for c in cof:\n if c in matrix:\n out += matrix[c]\n return out\n\n\n","sub_path":"ldist.py","file_name":"ldist.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"355193624","text":"import math\nfrom queue import PriorityQueue\n\nimport pygame\n\nfrom modules.graphic_util import *\n\n\ndef GBFSWithVisualizer(draw, grid, start, end):\n count = 0\n open_set = PriorityQueue()\n open_set.put((0, 0, start))\n came_from = {}\n g_score = {node: float(\"inf\") for row in grid for node in row}\n g_score[start] = 0\n f_score = {node: float(\"inf\") for row in grid for node in row}\n f_score[start] = manhattan(start.get_pos(), end.get_pos())\n\n visited_set = {start}\n\n while not open_set.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = open_set.get()[2]\n\n if current == end:\n reconstruct_path(came_from, end, draw, start)\n end.make_end()\n return True\n\n best_distance = float(\"inf\")\n best_neighbour = None\n for neighbor in current.neighbors:\n manhattan_distance = manhattan(neighbor.get_pos(), end.get_pos())\n if neighbor not in visited_set:\n came_from[neighbor] = current\n count += 1\n open_set.put((manhattan_distance, count, neighbor))\n visited_set.add(neighbor)\n neighbor.make_open()\n\n draw()\n\n if current != start:\n current.make_closed()\n\n return False\n\n\ndef manhattan(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return abs(x1 - x2) + abs(y1 - y2)\n","sub_path":"car-planning/algorithms/gbfs.py","file_name":"gbfs.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"566900416","text":"\n\nimport NERDA as nerda\nfrom NERDA.precooked import EN_ELECTRA_EN, EN_BERT_ML\nimport nltk\nfrom nltk.tokenize import word_tokenize\nimport torch\nfrom rbm.utils import plugins\nfrom rbm.backends import TorchBackend\nfrom rbm.backends.nlp import NER\n\n@plugins.register\nclass NERDA(TorchBackend, NER):\n variants = ['EN_ELECTRA_EN', 'EN_BERT_ML']\n\n def __init__(self, model_name, device, batch_size=1):\n TorchBackend.__init__(self, device=device)\n NER.__init__(self, batch_size=batch_size)\n self.model_name = model_name\n self.__name__ = model_name\n self._model = None\n\n def __call__(self, *args, **kwargs):\n model = eval(self.model_name)\n model = model(device=self.device)\n try:\n model.load_network()\n except (AssertionError, RuntimeError):\n model.download_network()\n model.load_network()\n try:\n nltk.data.find('tokenizers/punkt')\n except LookupError:\n nltk.download('punkt')\n self._model = model\n\n def preprocess(self, inputs):\n tokenized = [word_tokenize(_text) for _text in inputs]\n return tokenized\n\n def predict(self, inputs):\n return self._model.predict(inputs, batch_size=self.batch_size)\n\n\n","sub_path":"rbm/models/nlp/ner/nerda.py","file_name":"nerda.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"402532897","text":"\"\"\"\nCommand line interface for working with agent services\n\"\"\"\nfrom typing import List\nfrom uuid import UUID\n\nimport typer\n\nimport prefect\nfrom prefect.agent import OrionAgent\nfrom prefect.cli._types import PrefectTyper, SettingsOption\nfrom prefect.cli._utilities import exit_with_error\nfrom prefect.cli.root import app\nfrom prefect.client import get_client\nfrom prefect.exceptions import ObjectNotFound\nfrom prefect.settings import PREFECT_AGENT_QUERY_INTERVAL, PREFECT_API_URL\nfrom prefect.utilities.services import critical_service_loop\n\nagent_app = PrefectTyper(\n name=\"agent\", help=\"Commands for starting and interacting with agent processes.\"\n)\napp.add_typer(agent_app)\n\n\nascii_name = r\"\"\"\n ___ ___ ___ ___ ___ ___ _____ _ ___ ___ _ _ _____\n | _ \\ _ \\ __| __| __/ __|_ _| /_\\ / __| __| \\| |_ _|\n | _/ / _|| _|| _| (__ | | / _ \\ (_ | _|| .` | | |\n |_| |_|_\\___|_| |___\\___| |_| /_/ \\_\\___|___|_|\\_| |_|\n\n\"\"\"\n\n\n@agent_app.command()\nasync def start(\n # deprecated main argument\n work_queue: str = typer.Argument(\n None,\n show_default=False,\n help=\"DEPRECATED: A work queue name or ID\",\n ),\n work_queues: List[str] = typer.Option(\n None,\n \"-q\",\n \"--work-queue\",\n help=\"One or more work queue names for the agent to pull from.\",\n ),\n hide_welcome: bool = typer.Option(False, \"--hide-welcome\"),\n api: str = SettingsOption(PREFECT_API_URL),\n # deprecated tags\n tags: List[str] = typer.Option(\n None,\n \"-t\",\n \"--tag\",\n help=\"DEPRECATED: One or more optional tags that will be used to create a work queue\",\n ),\n):\n \"\"\"\n Start an agent process to poll one or more work queues for flow runs.\n \"\"\"\n work_queues = work_queues or []\n\n if work_queue is not None:\n # try to treat the work_queue as a UUID\n try:\n async with get_client() as client:\n q = await client.read_work_queue(UUID(work_queue))\n work_queue = q.name\n # otherwise treat it as a string name\n except (TypeError, ValueError):\n pass\n work_queues.append(work_queue)\n app.console.print(\n \"Agents now support multiple work queues. Instead of passing a single argument, provide work queue names \"\n f\"with the `-q` or `--work-queue` flag: `prefect agent start -q {work_queue}`\\n\",\n style=\"blue\",\n )\n\n if not work_queues and not tags:\n exit_with_error(\"No work queues provided!\", style=\"red\")\n elif work_queues and tags:\n exit_with_error(\n \"Either `work_queues` or `tags` can be provided, but not both.\", style=\"red\"\n )\n\n if tags:\n work_queue_name = f\"Agent queue {'-'.join(sorted(tags))}\"\n app.console.print(\n \"`tags` are deprecated. For backwards-compatibility with old \"\n f\"versions of Prefect, this agent will create a work queue named `{work_queue_name}` \"\n \"that uses legacy tag-based matching.\",\n style=\"red\",\n )\n\n async with get_client() as client:\n try:\n work_queue = await client.read_work_queue_by_name(work_queue_name)\n if work_queue.filter is None:\n # ensure the work queue has legacy (deprecated) tag-based behavior\n await client.update_work_queue(filter=dict(tags=tags))\n except ObjectNotFound:\n # if the work queue doesn't already exist, we create it with tags\n # to enable legacy (deprecated) tag-matching behavior\n await client.create_work_queue(name=work_queue_name, tags=tags)\n\n work_queues = [work_queue_name]\n\n if not hide_welcome:\n if api:\n app.console.print(\n f\"Starting v{prefect.__version__} agent connected to {api}...\"\n )\n else:\n app.console.print(\n f\"Starting v{prefect.__version__} agent with ephemeral API...\"\n )\n\n async with OrionAgent(work_queues=work_queues) as agent:\n if not hide_welcome:\n app.console.print(ascii_name)\n app.console.print(\n \"Agent started! Looking for work from \"\n f\"queue(s): {', '.join(work_queues)}...\"\n )\n\n await critical_service_loop(\n agent.get_and_submit_flow_runs,\n PREFECT_AGENT_QUERY_INTERVAL.value(),\n printer=app.console.print,\n )\n\n app.console.print(\"Agent stopped!\")\n","sub_path":"src/prefect/cli/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"323432468","text":"# -*- coding: utf-8 -*-\n#from beaker.middleware import SessionMiddleware\nfrom bottle import (\n abort, default_app, hook, static_file,\n TEMPLATE_PATH, jinja2_template, request, response\n)\nimport os\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom wordreg.config import config\nfrom wordreg.logger import create_logger\nfrom wordreg.model import UserAuthToken\n\nsession_opts = {\n \"session.type\": \"file\",\n \"session.data_dir\": \"./data\",\n \"session.cookie_expires\": True,\n \"session.auto\": True,\n}\n\napp = default_app()\napp.config.load_dict(config)\napp.log = create_logger(app.config[\"debug\"])\napp_root = os.path.dirname(os.path.abspath(__file__))\napp.config[\"app.root\"] = app_root\nTEMPLATE_PATH.append(os.path.join(app_root, \"templates\"))\n\nengine = create_engine(app.config[\"db_dsn\"], echo=True)\napp.engine = engine\napp.create_session = sessionmaker(bind=engine)\n\n\n@app.route(\"/\", name=\"static\")\ndef serve_static(file_name):\n return static_file(file_name, root=os.path.join(app.config[\"app.root\"], \"../../public\"))\n\n\n@hook(\"before_request\")\ndef before_request():\n request.session = request.environ.get(\"beaker.session\")\n request.db = app.create_session()\n\n\n@hook(\"after_request\")\ndef after_request():\n #response.headers['Access-Control-Allow-Origin'] = '*'\n request.db.commit()\n\n\ndef auth_required(callback):\n def check_auth_token(*args, **kwargs):\n authorization = request.get_header(\"Authorization\", \"\")\n if not authorization:\n abort(401, \"Authorization header required.\")\n token = request.session.get(\"user_auth_token\")\n #user_auth_token = request.db().query(UserAuthToken).filter_by(token=authorization).first()\n if not token:\n abort(401, \"Auth token not found.\")\n if token != authorization:\n abort(401, \"Auth token doesn't match\")\n return callback(*args, **kwargs)\n return check_auth_token\n\n\ndef template(file_path, **args):\n args.setdefault(\"get_url\", app.get_url)\n return jinja2_template(file_path, **args)\n\n\ndef db():\n return request.db\n\n\ndef session():\n return request.session\n","sub_path":"server/wordreg/webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"182544366","text":"#price of Premium ground shipping\npgs = 125.00\n\n#price of ground shipping cauculated by lbs\ndef ground_shipping(weight):\n if weight <= 2:\n return (20+(weight*1.50))\n elif weight > 2 and weight <= 6:\n return (20+(weight*3.00))\n elif weight > 6 and weight <= 10:\n return (20+(weight*4.00))\n else:\n return (20+(weight*4.75))\n\n#price of Drone shipping cauculated by lbs \ndef drone_shipping(weight):\n if weight <= 2:\n return (weight*4.50)\n elif weight > 2 and weight <= 6:\n return (weight*9.00)\n elif weight > 6 and weight <= 10:\n return (weight*12.00)\n else:\n return (weight*14.25)\n \ndef shipping_method(weight):\n x = ground_shipping(weight)\n print(\"Ground shipping price:\" + str(x))\n y = drone_shipping(weight)\n print(\"Drone shipping price:\" + str(y))\n if ground_shipping(weight) >= 125 and drone_shipping(weight) >= 125:\n return \"The shipping methoed that is de cheapest is Premium Shipping, it will cost: \" + \"$\" + str(pgs)\n if ground_shipping(weight) < drone_shipping(weight):\n return \"The shipping methoed that is de cheapest is Ground Shipping, it will cost: \" + \"$\" + str(x)\n else: \n return \"The shipping methoed that is de cheapest is Drone Shipping, it will cost: \" + \"$\" + str(y)\n \n \n#test shipping_method\nz = shipping_method(1)\nprint(z)\n","sub_path":"shipping/shipping.py","file_name":"shipping.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"398419791","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport MODULOS.Location as lc\r\n\r\npath_0 = os.getcwd()\r\n\r\n# TRAIN\r\n\r\ntabla_1_train = pd.read_excel(path_0 + '/Data/df_train_0.xlsx', index_col = 'id' )\r\ntabla_1_train = tabla_1_train[['latitud', 'longitud', 'valormetrocuadrado']]\r\ntabla_1_train['sesgo'] = 0.0\r\n\r\ntabla_3_train = tabla_1_train.copy()\r\n\r\ntabla_2_train = pd.read_excel(path_0 + '/Data/Scores/score_catastro.xlsx', index_col = 'id')\r\ntabla_2_train.columns = ['score_catastro']\r\ntabla_2_train[tabla_2_train['score_catastro'] == 0] = tabla_2_train[tabla_2_train!=0].min()[0] # MINIMO\r\n\r\ntabla_1_train['score_catastro'] = tabla_2_train\r\n\r\n# TEST\r\n\r\ntabla_1_test = pd.read_excel(path_0 + '/Data/df_test_0.xlsx', index_col = 'id' )\r\ntabla_1_test = tabla_1_test[['latitud', 'longitud', 'valormetrocuadrado']]\r\ntabla_1_test['sesgo'] = 0.0\r\n\r\ntabla_3 = tabla_1_test.copy()\r\n\r\ntabla_2_test = pd.read_excel(path_0 + '/Data/Scores_test/score_catastro.xlsx', index_col = 'id')\r\ntabla_2_test.columns = ['score_catastro']\r\ntabla_2_test[tabla_2_test['score_catastro'] == 0] = tabla_2_test[tabla_2_test!=0].min()[0] # MINIMO\r\n\r\ntabla_1_test['score_catastro'] = tabla_2_test\r\n\r\nmodelo_factores = 0.06 # FACTOR MODEL\r\n\r\ntabla_1 = tabla_1_train.append(tabla_1_test)\r\n\r\n#for i in range(0, 10):\r\nfor i in range(0, tabla_1_test.shape[0]):\r\n #break\r\n \r\n # VALIDADOR PRECIO LAST CONTRA PRECIO CATASTRO\r\n if tabla_1_test.iloc[i, 2] < tabla_1_test.iloc[i, 4]: continue\r\n \r\n # ESTOS CAMPOS PODRIAN CAMBIAR\r\n lat_ = tabla_1_test.iloc[i,0]\r\n lon_ = tabla_1_test.iloc[i,1]\r\n \r\n score_ = lc.Prima_df(lat_, lon_, tabla_1, 0.3)\r\n score_.get_score()\r\n \r\n df_ = score_.df.copy()\r\n df_[df_['dist_rel'] == 1.0]\r\n \r\n if df_.shape[0] == 0: continue\r\n \r\n df_['valormetrocuadrado_val'] = df_['valormetrocuadrado'] \r\n \r\n for u in range(100):\r\n \r\n df_['sesgo_val'] = list(np.random.uniform(low = -0.05 , high = 0, size = df_.shape[0]))\r\n df_['Y_prima'] = df_['valormetrocuadrado'] * ( 1 + df_['sesgo_val'])\r\n\r\n if df_['Y_prima'].std() < df_['valormetrocuadrado_val'].std():\r\n \r\n df_['sesgo'] = df_['sesgo_val'] \r\n df_['valormetrocuadrado_val'] = df_['valormetrocuadrado'] * ( 1 + df_['sesgo_val'])\r\n \r\n #print((df_['valormetrocuadrado'] * ( 1 + df_['sesgo'])).std())\r\n\r\n tabla_1.update(df_['sesgo'])\r\n \r\n print(i, ' / ', tabla_1_test.shape[0])\r\n\r\ntabla_1['valormetrocuadrado'] = tabla_1['valormetrocuadrado'] * (1 + tabla_1['sesgo'])\r\ntabla_1 = tabla_1.loc[tabla_1_test.index]\r\ntabla_1 = tabla_1['valormetrocuadrado']\r\ntabla_1.to_excel(path_0 + '/Data/df_Y_prima_test.xlsx')\r\n\r\n","sub_path":"get_Y_prima_test.py","file_name":"get_Y_prima_test.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99010359","text":"import sys\nimport os\nimport copy\nimport time\n\n#for Jira control\nfrom jira import JIRA\nfrom jira.exceptions import JIRAError\n\n#for excel control\nimport xlsxwriter as xlswt\nimport openpyxl as xlsrd\n#for time\nfrom datetime import datetime\n# for UI\n#from PyQt5 import uic, QtWidgets, QtGui\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\n# dir(jira)\n# dir(jira.JIRA)\n# hasattr(JIRA, crete_issue)\n\n\n#http://hlm.lge.com/issue/rest/api/2/issue/GSWDIM-22476/\n\n#http://hlm.lge.com/issue/rest/api/2/issue/TVPLAT-3963/\n#http://hlm.lge.com/issue/rest/api/2/issue/TVPLAT-3963/editmeta\n\n#http://hlm.lge.com/qi/rest/api/2/issue/QEVENTSEVT-7232/ - Q\n\n\nDevTracker = 'http://hlm.lge.com/issue'\nQTracker = 'http://hlm.lge.com/qi'\n\n\n# Excel\nexcel_file = None\nwsheet = None\n# Jira\ndev_jira = False\nq_jira = False\n\ndissue_dict = {}\ndissue_init_dict = {\n 'project': {'key': ''},\n 'components' : [ ],\n 'summary': '',\n 'description': '',\n 'parent' : { 'id' : ''},\n 'issuetype' : { 'name' : '' },\n #'issuetype': {'id': '5'},\n 'assignee': { },\n 'reporter': { },\n 'labels' : [ ],\n 'duedate' : '',\n #'customfield_10105' :[{\"name\":\"sungbin.na\",\"key\":\"sungbin.na\",\"emailAddress\":\"sungbin.na@lge.com\" },] #watchers\n 'customfield_10105' :[ ], #watchers\n 'customfield_10436':'', # Epic Name\n #'comment' : { 'comments' : [ { 'body' : ''}, ] }, #comment\n}\n\nIslogin = False\nIsexcelloaded = False\n\n\ndef makeKeyList(ws) :\n # read header and make key list to make jira json file\n keylist = []\n j = 1\n cols = ws.columns\n for col in cols :\n val = ws.cell(row = 1, column = j).value\n if(val is not None):\n keylist.append(val)\n j+=1\n else :\n pass\n return keylist\n\ndef setProject(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n dissue_dict[keyword]['key'] = value\n else :\n print(keyword, \" = None... Skip\")\n\n\ndef setComponents(keyword, value) :\n if(value is not None):\n value = str(value)\n print(keyword, \" = \", value)\n comp_list = value.split(',')\n print(comp_list)\n comp_dict = { 'name' : ''}\n for cl in comp_list :\n comp_dict['name'] = cl.strip()\n dissue_dict[keyword].append(comp_dict)\n #print(comp)\n #print(dissue_dict[keyword])\n else :\n del dissue_dict[keyword]\n print(keyword, \" = None... Skip\")\n\n\ndef setIssueType(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n dissue_dict[keyword]['name'] = value.strip()\n else :\n dissue_dict[keyword]['name'] = 'Task'\n print(keyword, \" = None... Set Default - Task\")\n\ndef setParent(keyword, value) :\n if(value is not None):\n if(dissue_dict['issuetype']['name'] == 'Sub-task') :\n print(keyword, \" = \", value)\n dissue_dict[keyword]['id'] = value\n else :\n del dissue_dict[keyword]\n print(\"Issue type is not Sub-Task.... No need to set parent id... delete this keyword\")\n else :\n if(dissue_dict['issuetype']['name'] == 'Sub-Task') :\n print(\"[Err] Issue type is Sub-Task.... Need to set parent id...\")\n else :\n del dissue_dict[keyword]\n print(keyword, \" = Issue type is not Sub-Task, No need to set parent id... delete this keyword\")\n\ndef setEpicName(keyword, value) :\n if(value is not None):\n print(\"************************\")\n print(keyword, \" = \", value)\n if(dissue_dict['issuetype']['name'] == 'Epic') :\n dissue_dict['customfield_10436'] = value\n else :\n del dissue_dict['customfield_10436']\n print(\"Issue type is not Epic.... No need to set Epic Name... delete this keyword\")\n else :\n if(dissue_dict['issuetype']['name'] == 'Epic') :\n print(\"[Err] Issue type is Epic.... Need to set Epic Name...\")\n else :\n del dissue_dict['customfield_10436']\n print(keyword, \" = Issue type is not Epic, No need to set Epic Name... delete this keyword\")\n\n\ndef setSummarynDescription(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n dissue_dict[keyword] = value.strip()\n else :\n if(keyword == 'summary') :\n dissue_dict[keyword] = 'Set Default Summary - Please change the summary later'\n elif (keyword == 'description') :\n dissue_dict[keyword] = 'Set Default Description - Please change the Description later'\n else :\n print(keyword, \" = None... Skip\")\n\ndef setAssigneenReporter(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n dissue_dict[keyword]['name'] = value.strip()\n else :\n if(keyword == 'assignee') :\n dissue_dict[keyword]['name'] = None\n elif (keyword == 'reporter') :\n dissue_dict[keyword]['name'] = 'hlm-admin'\n else :\n print(keyword, \" = None... Skip\")\n\ndef setWatchers(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n watcher_list = value.split(',')\n #print(watcher_list)\n for watcher in watcher_list :\n watcher_dict = { 'name' : ''}\n watcher_dict['name'] = watcher.strip() # delete space\n dissue_dict['customfield_10105'].append(watcher_dict)\n #print(\"========================\")\n #print(watcher.strip())\n else :\n del dissue_dict['customfield_10105']\n print(keyword, \" = None... Skip\")\n\ndef setDuedate(keyword, value) :\n if(value is not None):\n #duedate = datetime.strptime(value, '%Y-%m-%d')\n print(keyword, \" = \", value)\n dissue_dict[keyword] = str(value)\n else :\n del dissue_dict[keyword]\n print(keyword, \" = None... Skip\")\n\ndef setLabels(keyword, value) :\n if(value is not None):\n label_list = value.split(',')\n print(label_list)\n for label in label_list :\n dissue_dict[keyword].append(label)\n else :\n del dissue_dict[keyword]\n print(keyword, \" = None... Skip\")\n\ndef setComment(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n #dissue_dict['comment']['comments']['0']['body'] = value\n #'comment' : { 'comments' : [ { 'body' : ''}, ] }, #comment\n else :\n print(keyword, \" = None... Skip\")\n\ndef setAttachment(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n else :\n print(keyword, \" = None... Skip\")\n\ndef setCommonNotice(keyword, value) :\n if(value is not None):\n print(keyword, \" = \", value)\n desc = dissue_dict['description']\n desc = str(desc) + '\\\\n\\\\n' + str(value)\n dissue_dict['description'] = desc\n #print(\"========================\")\n #print(dissue_dict['description'])\n #print(\"========================\")\n else :\n print(keyword, \" = None... Skip\")\n\n\ndef makeDevJiraJSON(key, value) :\n if (key == 'project') :\n setProject(key, value)\n elif (key == 'components'):\n setComponents(key, value)\n elif (key == 'issuetype'):\n print(key + ' = ' + value)\n setIssueType(key, value)\n elif (key == 'parent'):\n setParent(key, value)\n elif (key == 'Epic Name'):\n setEpicName(key, value)\n elif (key == 'summary'):\n setSummarynDescription(key, value)\n elif (key == 'description'):\n setSummarynDescription(key, value)\n elif (key == 'assignee'):\n setAssigneenReporter(key, value)\n elif (key == 'reporter'):\n setAssigneenReporter(key, value)\n elif (key == 'watcher'):\n setWatchers(key, value)\n elif (key == 'duedate'):\n setDuedate(key, value)\n elif (key == 'labels'):\n setLabels(key, value)\n elif (key == 'comment'):\n setComment(key, value)\n elif (key == 'attachment'):\n print(\"Set attachment\")\n elif (key == 'Common Notice'):\n setCommonNotice(key, value)\n else :\n print(\"[Skip] Column - Unregistered key or field = \", key)\n\n\nform_class = uic.loadUiType(\"./QtUI/MainDialog.ui\")[0];\n\n#class MyWindow(QMainWindow):\nclass MyWindow(QMainWindow, form_class) :\n def __init__(self):\n super().__init__();\n self.setupUi(self);\n\n self.setWindowTitle(\"DevTracker Jira Creator from Excel\");\n self.Path.setText(\"Please select Excel file..........\")\n self.Path.setReadOnly(True)\n\n self.ProgressBar.setMinimum(0)\n self.ProgressBar.setMaximum(100)\n self.ProgressBar.setValue(0)\n\n self.FileSelectionBtn.setEnabled(False)\n self.CreateBtn.setEnabled(False)\n\n self.UserID.setFocus()\n\n self.LoginBtn.clicked.connect(self.userLogin)\n self.CreateBtn.clicked.connect(self.createJiraIssue)\n self.ExitBtn.clicked.connect(appexit)\n self.FileSelectionBtn.clicked.connect(self.openFileNameDialog)\n #self.SaveInfo.clicked.connect(self.SaveInfoClicked)\n\n\n def userLogin(self) :\n global dev_jira\n global q_jira\n print(\"userLogin\")\n userID = self.UserID.text()\n userPasswd = self.Passwd.text()\n try :\n dev_jira = JIRA(DevTracker, basic_auth = (userID, userPasswd))\n q_jira = JIRA(QTracker, basic_auth = (userID, userPasswd))\n except JIRAError as e:\n if e.status_code == 401 :\n print(\"[Error] Login Fail.. Please Check ID/Passwd and Try again!\")\n print(e)\n else :\n Islogin = True\n self.FileSelectionBtn.setEnabled(True)\n self.CreateBtn.setEnabled(False)\n print(\"userLogin=\", Islogin)\n finally :\n print(\"Login Try/Exception routine is passed!\")\n pass\n\n\n def openFileNameDialog(self):\n global wsheet\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(self,\"QFileDialog.getOpenFileName()\", \"\",\"Exel Files (*.xlsm);;Exel Files (*.xls)\", options=options)\n if fileName:\n self.Path.setText(fileName)\n excel_file = xlsrd.load_workbook(fileName)\n wsheet = excel_file['Dev Tracker']\n Isexcelloaded = True\n self.FileSelectionBtn.setEnabled(True)\n self.CreateBtn.setEnabled(True)\n self.ProgressBar.setValue(0)\n\n #print(\"==========================================\")\n #print(jira_keylist)\n #print(\"==========================================\")\n else :\n Isexcelloaded = False\n self.CreateBtn.setEnabled(False)\n\n '''\n def openFileNamesDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n files, _ = QFileDialog.getOpenFileNames(self,\"QFileDialog.getOpenFileNames()\", \"\",\"All Files (*);;Python Files (*.xlsm)\", options=options)\n if files:\n print(files)\n\n def saveFileDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getSaveFileName(self,\"QFileDialog.getSaveFileName()\",\"\",\"All Files (*);;Text Files (*.xlsm)\", options=options)\n if fileName:\n print(fileName)\n\n def SaveInfoClicked(self) :\n \tprint(\"SaveInfoClicked\")\n '''\n\n def createJiraIssue(self) :\n print(\"createJiraIssue\")\n global dissue_dict\n global dev_jira\n global q_jira\n\n self.ProgressBar.setValue(0)\n i = 1; j = 1\n rows = wsheet.rows\n jira_keylist = makeKeyList(wsheet)\n\n row_count = wsheet.max_row\n col_count = wsheet.max_column\n print('wsheet.max_row =', row_count)\n print('wsheet.max_col =', col_count)\n\n if (os.path.isfile(\"logfile.txt\")) :\n os.remove(\"logfile.txt\")\n\n log = open('logfile.txt', 'wt')\n\n '''\n update_dict = {\n 'customfield_10105' :[ {\"name\":\"\" },], #watchers\n }\n '''\n for row in rows :\n if(i == 1) : i+=1; j = 1; continue\n\n if(wsheet.cell(row = i, column = 2).value) : # if project is not null - create issue\n dissue_dict = copy.deepcopy(dissue_init_dict)\n msg = \"\\n######## Row = %d Creating issues. #######\\n\" % i\n print(msg)\n log.write(msg)\n\n for key in jira_keylist :\n if(key == 'key') :\n j = 2; continue\n if(key == 'Common Notice') :\n val = wsheet.cell(row = 2, column = j).value\n else :\n val = wsheet.cell(row = i, column = j).value\n #print(\"=====================\")\n #print(key, val)\n #print(\"=====================\")\n makeDevJiraJSON(key, val)\n j += 1\n try :\n print(\"========================================================\")\n print(dissue_dict)\n log.write(str(dissue_dict))\n new_dissue = dev_jira.create_issue(fields= dissue_dict)\n #dev_jira.revmove_watcher(new_dissue, 'sungbin.na')\n new_dissue.update(fields=update_dict)\n #createdkey = new_dissue.raw['key']\n #print(\"Created Key = \", createdkey)\n #wsheet.cell(row = i, column = 1).value = createdkey\n print(\"========================================================\")\n except Exception as e:\n log.write(str(e))\n print(e)\n\n else :\n msg = \"\\nRow = %d��° Issue ���� Skip �մϴ�.\\n\" % i\n print(msg)\n log.write(msg)\n pass\n\n progressing = int(i*100/row_count)\n self.ProgressBar.setValue(progressing)\n self.ProgressBar.update()\n i += 1\n\n log.close()\n\n\ndef appexit() :\n print(\"appexit\")\n sys.exit()\n\n\nif __name__ == \"__main__\" :\n\tapp = QApplication(sys.argv);\n\tmyWindow = MyWindow();\n\tmyWindow.show();\n\tapp.exec_();\n","sub_path":"JIRAControl/CreateJiraFromXls_UI.py","file_name":"CreateJiraFromXls_UI.py","file_ext":"py","file_size_in_byte":14373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"444824679","text":"import pyautogui, pyperclip\nfrom time import sleep\nimport random\nprint(\"TOOL SPAM TIN NHẮN FACEBOOK | HOANGTUYEN\")\n\n\nmess = input(\"Nhập tin nhắn cần spam: (Tin nhắn 1 | tin nhắn 2 | tin nhắn 3) : \").split(\" | \")\nn = int(input(\"Nhập số lần spam:\"))\n\nprint(\"Chuẩn bị spam . . .\")\nfor i in range(10, 0, -1):\n print(i, end=\"...\", flush=True)\nprint(\"Bắt đầu spam . . . \")\n\nfor i in range(n):\n pyperclip.copy(random.choice(mess))\n pyautogui.hotkey(\"ctrl\", \"v\")\n pyautogui.press(\"enter\")\n sleep(0.5)\n\nprint(\"Đã spam xong . . . . \")\n\n","sub_path":"TH2/spam_mess.py","file_name":"spam_mess.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"653993396","text":"from tree import tree_node as node\nfrom tree import tree_node\nfrom tree import tree_edge as egde\nfrom tree import tree\nfrom copy import deepcopy\n\nclass specie(tree_node):\n\t\n\tdef __init__(self, r = None, name = None, theta = None):\n\t\t\n\t\tnode.__init__(self)\n\t\tself.R = set()\n\t\tself.name = name\n\t\tself.theta = theta\n\t\t\n\t\tif r: \n\t\t\tself.r = r\n\t\t\tself.R.add(r)\n\t\telse:\n\t\t\tself.r = None\n\n\tdef copy(self):\n\t\ts = specie(self.r, self.name)\n\t\ts.R = self.R\n\t\treturn s\n\nclass genetic_tree(tree):\n\t\n\tdef copy(self):\n\t\t\n\t\tt = genetic_tree()\n\t\t\n\t\tfor edg in self.edges:\n\t\t\ts = edg.source\n\t\t\td = edg.destination\n\t\t\t\n\t\t\ts_in_tree = t.get_node(self.by_name(s.name))\n\t\t\td_in_tree = t.get_node(self.by_name(d.name))\n\t\t\t\n\t\t\tif not s_in_tree: s_in_tree = tree_node(name = s.name)\n\t\t\tif not d_in_tree: d_in_tree = tree_node(name = d.name)\n\t\t\t\n\t\t\tt.add_edge(s_in_tree, d_in_tree)\n\t\t\n\t\troot = self.get_root()\n\t\tnew_root = t.get_node(self.by_name(root.name))\n\t\tt.root = new_root\n\t\t\n\t\tfor specie in self.nodes:\n\t\t\tnew_tree_specie = t.get_node(self.by_name(specie.name))\n\t\t\tnew_tree_specie.r = specie.r\n\t\t\tnew_tree_specie.R = set(specie.R)\n\t\t\n\t\treturn t\n\t\n\tdef __cmp__(self, other):\n\t\treturn cmp(self.__str__(), other.__str__())\n\t\t\n\tdef __hash__(self):\n\t\treturn id(self)\n\t\n\tdef __repr__(self):\n\t\treturn str(dict((node.name, node.r ) for node in self.nodes))\n\t\t\n\tdef __str__(self):\n\t\treturn str(self.__repr__())\n\n","sub_path":"fitch/src/graph/genetic_tree.py","file_name":"genetic_tree.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"319003375","text":"import urllib.request\n\nimport pytest\n\nfrom woodwork import DataTable\nfrom woodwork.demo import load_retail\nfrom woodwork.logical_types import (\n Boolean,\n Categorical,\n Datetime,\n Double,\n Integer,\n NaturalLanguage\n)\n\n\n@pytest.fixture(autouse=True)\ndef set_testing_headers():\n opener = urllib.request.build_opener()\n opener.addheaders = [('Testing', 'True')]\n urllib.request.install_opener(opener)\n\n\ndef test_load_retail_diff():\n nrows = 10\n df = load_retail(nrows=nrows, return_dataframe=True)\n assert df.shape[0] == nrows\n nrows_second = 11\n df = load_retail(nrows=nrows_second, return_dataframe=True)\n assert df.shape[0] == nrows_second\n\n assert 'order_product_id' in df.columns\n assert df['order_product_id'].is_unique\n\n\ndef test_load_retail_datatable():\n dt = load_retail(nrows=10, return_dataframe=False)\n assert isinstance(dt, DataTable)\n\n expected_logical_types = {\n 'order_product_id': Categorical,\n 'order_id': Categorical,\n 'product_id': Categorical,\n 'description': NaturalLanguage,\n 'quantity': Integer,\n 'order_date': Datetime,\n 'unit_price': Double,\n 'customer_name': Categorical,\n 'country': Categorical,\n 'total': Double,\n 'cancelled': Boolean,\n }\n\n for column in dt.columns.values():\n assert column.logical_type == expected_logical_types[column.name]\n\n assert dt.index == 'order_product_id'\n assert dt.time_index == 'order_date'\n assert dt.columns['order_product_id'].semantic_tags == {'index'}\n assert dt.columns['order_date'].semantic_tags == {'time_index'}\n","sub_path":"woodwork/tests/demo_tests/test_retail.py","file_name":"test_retail.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"408402260","text":"import math\nfrom scipy import optimize\nimport numpy as np\nimport random\nimport xlrd\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\npi = math.pi\n\n\ndef fa_dasu(v_2d, syudan, n):\n # 第一のヒューリスティックに関する計算\n # 周囲のエージェントの存在を認知する\n fa_syudan = np.full(n, 10)\n syudan_ato = syudan + v_2d\n for i in range(n):\n #print(\"i\", fa_syudan[i])\n soutai = syudan_ato - syudan_ato[i]\n #soutaiはsyudanから自分の位置を引いたも and\n #print(\"soutai\", soutai)\n for j in range(n):\n if soutai[j, 0] == 0 and soutai[j, 1] == 0:\n continue\n if abs(soutai[j,0]) <= 60 / 220 and abs(soutai[j,1]) <= 60 / 220:\n kyori = np.linalg.norm(soutai[j])\n\n #print(\"距離は\",kyori)\n if kyori <= 10:\n fa_syudan[i] = kyori\n\n return fa_syudan\n\ndef fa_dasukai(v_2d, syudan, n):\n # 第一のヒューリスティックに関する計算\n # 周囲のエージェントの存在を認知する\n fa_syudan = np.full(n, 10)\n syudan_ato = syudan + v_2d\n for i in range(n):\n #print(\"i\", fa_syudan[i])\n soutai = syudan_ato - syudan_ato[i]\n #soutaiはsyudanから自分の位置を引いたも and\n #print(\"soutai\", soutai)\n\n\n for j in range(n):\n if soutai[j, 0] == 0 and soutai[j, 1] == 0:\n continue\n if abs(soutai[j,0]) <= 60/220 and abs(soutai[j,1]) <= 60/220:\n kyori = np.linalg.norm(soutai[j])\n #if kyori<=60/220 and\n #print(\"距離は\",kyori)\n if kyori < 10:\n fa_syudan[i] = kyori\n\n return fa_syudan\n\n\n# 関数を変更位させるnumpyの配列に対応\ndef hulistics_1(fa, alpha0,n):\n # 目的関数\n Dmax = 10\n\n \"\"\"def objective_function(theta, arufa):\n return (Dmax**2)+(fa**2)-(2*Dmax*fa*math.cos(arufa-theta))\"\"\"\n\n #alpha0 = alpha0.astype(np.float32)\n\n for i in range(n):\n # 歩行者の半径を考慮したものに\n def fufu(theta):\n return (Dmax ** 2) + (fa[i] ** 2) - (2 * Dmax * fa[i] * math.cos(alpha0[i] - theta))\n\n nagasa =(fa[i]**2 - (60/220)**2)**0.5\n #print(\"食べたい\", nagasa)\n #print(\"nagasa\", type(nagasa), \"nagasa\", nagasa)\n\n\n kakudo_gosa = np.arctan((60/220)/nagasa)\n #print(\"kakudo_gosa\", kakudo_gosa)\n #print(\"dtype of fa, alpha0,n\", type(alpha0), type(fa), type(kakudo_gosa))\n #print(\"alpha0とはいったい\",alpha0[i])\n #alpha0[i] = alpha0.astype(np.float32)\n #min = optimize.fmin(fufu, (alpha0[i] - math.pi/2),(alpha0[i] + math.pi/2) )\n min1 = optimize.fminbound(fufu, alpha0[i] - math.pi/2, alpha0[i] - kakudo_gosa)\n min2 = optimize.fminbound(fufu, alpha0[i] + kakudo_gosa, alpha0[i] + math.pi/2)\n\n min_1 = alpha0[i] - abs(alpha0[i] - min1)\n min_2 = alpha0[i] - abs(alpha0[i] - min2)\n #print(\"min1\", \"min2\", \"min3\", min1, min2, alpha0[i])\n if min_1 >= min_2:\n alpha0[i] = min1\n else:\n alpha0[i] = min2\n\n return alpha0\n\n\ndef cal_fij(n, syudan):\n # この関数は大幅に縮小できる気がする一応実装修了\n fij = np.zeros([n, 2])\n #print(\"fij\", fij)\n for i in range(n):\n fij_i = np.zeros(2)\n soutai = syudan - syudan[i, :]\n #print(\"soutaiそうたい\", soutai)\n #print(\"次は\", soutai[i, :])\n dij = np.zeros(n)\n for i in range(n):\n dij[i] = np.linalg.norm(soutai[i, :])\n #print(\"距離は\", dij)\n\n if dij[i] <= 60 / 220 and dij[i] > 0:\n nij = soutai / dij\n fij = 5000 * 9.8 * (60 / 220 + 60 / 220 - dij) * nij\n fij_i += fij\n #print(\"fijの\", i, \"番目は\", fij_i)\n\n fij[i, :] += fij_i\n return fij\n\n\n# 壁との接触する関数 車として考える\n\nwall = np.zeros([4, 2])\n\nfor i in range(4):\n wall[i, 0] = 10 * random.random()\n wall[i, 1] = 10 * random.random()\n\n\n# 人と壁の数が一致しないことに注意\n# 壁の数をforループしていく流れにする\n\ndef cal_fiw(n, syudan):\n fiw = np.zeros([n, 2])\n for i in range(n):\n fiw_i = np.zeros(2)\n soutai = wall - syudan[i, :]\n diw = np.zeros(n)\n for i in range(n):\n diw[i] = np.linalg.norm(soutai[i, :])\n\n if diw[i] <= 60 / 220 and diw[i] > 0:\n niw = soutai / diw\n fiw = 5000 * 9.8 * (60 / 220 + 60 / 220 - diw) * niw\n fiw_i += fiw\n #print(\"fiwの\", i, \"番目は\", fiw_i)\n\n fiw[i, :] += fiw_i\n return fiw\n\n\ndef dvdt(n, v_2d, alpha,fij):\n #この関数はつかわない\n #print(\"v_2dの説明\",v_2d)\n dvdt = np.zeros([n, 2])\n\n for i in range(n):\n dvdt[i, 0] = (v_2d[i,0]-1.7*np.cos(alpha[i]))/0.5 + fij[i,0]\n\n #dvdt[i, 0] = (v_2d[i, 0] - 1.7 * np.cos(alpha(i))) / 0.5 + fij(i, 0) + fiw(i, 0)\n dvdt[i, 1] = (v_2d[i,1]-1.7*np.sin(alpha[i]))/0.5 + fij[i,1]\n v_2d += dvdt\n\n return v_2d\n\ndef dasu_v_1d(v_2d,v_1d,n):\n for i in range(n):\n v_1d[i] = np.linalg.norm(v_2d[i])\n return v_1d\n\n\n","sub_path":"model/moussaif.py","file_name":"moussaif.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"482295443","text":"''' \ncrawl reports from google\nlast modified by zw\n'''\nimport time\nfrom selenium import webdriver\nimport re\nfrom bs4 import BeautifulSoup\nimport json\nimport io\nimport os\nfrom os.path import join as pjoin\n\nimport urllib.parse # url coding\nimport requests\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport socket\nimport random\nimport hashlib\n\n# 将selenium改成不阻塞\ndesired_capabilities = DesiredCapabilities.CHROME\ndesired_capabilities[\"pageLoadStrategy\"] = \"none\"\n\nROOT_PATH = os.path.dirname('.')\ndelete_list = ['snopes.com', 'politifact.com', 'factcheck.org', 'checkyourfact.com']\n\n\nclass GoogleScholarCommon():\n\n # 这里url是要搜索的关键词\n def __init__(self, wait_time=5, url=\"https://www.google.com/search?q=\", ds_name='test'):\n self.dataset_name = ds_name\n self.gs_url = url\n self.driver = webdriver.Chrome(\"chromedriver.exe\") # 需要chromedriver\n self.wait_time = wait_time\n self.source = self.driver.page_source\n\n def search_cite(self):\n \"\"\"搜索website并返回\n \"\"\"\n claim_reports = dict()\n claim_reports['reports'] = []\n\n self.driver.get('https://www.google.com/')\n self.driver.implicitly_wait(self.wait_time)\n input_box = self.driver.find_element_by_css_selector(\"input[name='q']\") # 查找元素\n submit_btn = self.driver.find_element_by_css_selector(\"input[name='btnK']\")\n # 清空已有搜索词 keyword=u'中国'\n input_box.click()\n input_box.clear()\n\n # 自动填入-搜索词,提交\n claim_reports['claim'] = self.gs_url\n input_box.send_keys(self.gs_url)\n submit_btn.submit()\n self.driver.implicitly_wait(self.wait_time) # 等待时间\n time.sleep(random.uniform(1.2, 2.1)) # 避免机器人,原理同上\n\n # 定位超链接, 循环点击爬取\n\n all_title_links = []\n N_page = 2\n while (N_page):\n source = self.driver.page_source # 扒取网页源码\n # bf = BeautifulSoup(source, \"lxml\")\n # filtering delete_list !!!!! #soup.find_all(\"div\", class_=\"g\")\n # all_title_links += self.filtering(bf.select('div.yuRUbf>a'), delete_list)\n all_title_links += re.findall(r'https://translate.google.com/translate\\?hl=zh-TW&sl=en&u=(.*?)\\&', source)\n time.sleep(random.uniform(2, 2.5)) # 避免机器人,原理同上\n # 爬取下一页\n print(all_title_links)\n self.driver.find_element_by_id('pnnext').click() # 设置下一页内容\n # self.driver.find_element_by_partial_link_text(\"下一頁\").click()\n N_page = N_page - 1\n time.sleep(random.uniform(1.5, 2)) # 避免机器人,原理同上\n\n # items = self.driver.find_elements_by_xpath('//*[@class=\"yuRUbf\"]/a')\n counts = len(all_title_links)\n print(counts)\n # for i in range(counts):\n # report = dict() # 返回的reports\n # # 每次循环,都重新获取元素,防止元素失效或者页面刷新后元素改变了\n # items = self.driver.find_elements_by_xpath('//*[@class=\"yuRUbf\"]/a')\n\n # 循环点击获取的元素 \n # items[i].click() # 先点击-> link\n # link = self.driver.current_url\n # link = all_title_links[i].get('href') # get_attribute\n # print(link)\n # report_content, is_report = self.download_the_page(link)\n # 打印每次获取元素,调试用\n # print(link)\n # link_id = hashlib.md5(link.encode('utf-8')).hexdigest()\n\n # report['claim'] = self.gs_url\n # report['report_link'] = link\n # report['report_content'] = report_content\n # report['report_is_report'] = is_report\n\n # 隐式等待,避免页面加载慢获取元素失败导致点击失效\n # time.sleep(1) # 避免机器人,原理同上\n # self.driver.back() # 后退\n # time.sleep(random.uniform(1, 2)) # 避免机器人,原理同上\n # source = self.driver.page_source # 扒取网页源码\n\n # saving\n # claim_reports['reports'].append(report)\n\n # self.write2file(pjoin(ROOT_PATH, f'snopes/{self.dataset_name}/{_generate_uid()}.json'), claim_reports)\n\n # links = re.findall(r'https://webcache.googleusercontent.com/search\\?q=.*?https://(.*?)\\+\\&', source)\n # print(re.findall(r'https://webcache.googleusercontent.com/search\\?q=.*?https://(.*?)\\+\\&', source)) # 模式匹配得到搜索结果\n # time.sleep(4) # 避免机器人,原理同上\n # # 这里在做模拟点击下一页,注意,这里下一页,需要特地设置。模拟点击后操作和之前一样\n # self.driver.find_element_by_id('pnnext').click() # 设置下一页内容\n # source = self.driver.page_source\n # print(re.findall(r'https://webcache.googleusercontent.com/search\\?q=.*?https://(.*?)\\+\\&', source))\n # 关闭\n self.driver.quit()\n\n def download_the_page(self, url):\n socket.setdefaulttimeout(5)\n # proxies = get_proxies(proxy_pool)\n # print(proxies)\n try:\n print(\"download the page...\")\n html = requests.get(url, timeout=(8, 9)).text\n except requests.exceptions.RequestException as err:\n print(err)\n return None, False\n except socket.timeout as tout:\n print(tout)\n return None, False\n bs = BeautifulSoup(html, 'html.parser')\n p_items = bs.find_all('p')\n text_list = []\n for p_item in p_items:\n p_text = p_item.text.strip()\n if judge_text(p_text):\n text_list.append(p_text)\n is_report = judge_report(text_list)\n report_content = '\\n'.join(text_list)\n print(url)\n print(report_content)\n return report_content, is_report\n\n def filtering(self, all_title_links, delete_list):\n # bf.select('div > div > a[href^=\"/url?q=https://www.\"]')[0]['href']\n # link { h3}\n ret_links = []\n for i, link in enumerate(all_title_links):\n # delete links if they are in link['href']\n continue_flag = False\n for ditem in delete_list:\n if ditem in link.get('href'):\n continue_flag = True\n break\n if continue_flag: continue\n ret_links.append(link)\n return ret_links\n\n def write2file(self, out_path, data):\n with io.open(out_path, 'ab+') as data_file:\n data = json.dumps(data, ensure_ascii=False, indent=4)\n data_file.write(data.encode('utf8', 'replace'))\n print(f'##save at {out_path}')\n\n\ndef judge_text(text):\n if text == '':\n return False\n if '\\n\\n' in text:\n return False\n return True\n\n\ndef judge_report(text_list):\n if len(text_list) < 3:\n return False\n return True\n\n\nimport time\n\n\ndef _generate_uid():\n n = 0\n previous_time = ''\n current_time = str(time.strftime(\"%Y%m%d%H%M%S\", time.localtime()))[2:]\n if previous_time != current_time:\n n = 0\n n = n + 1\n previous_time = current_time\n # return str(current_time) + '%02d' % n + '%02d' % random.randint(10,99)#'%02d' % n\n return str(current_time) + '%02d' % random.randint(10, 99)\n\n\n# _generate_code = _generate_code_func()\n\nif __name__ == \"__main__\":\n with open(\"test_links.txt\", \"r\") as f: # 打开文件读取信息\n for line in f.readlines():\n line = line.strip('\\n') # 去掉列表中每一个元素的换行符\n print(re.findall(r'https://www.google.com/search\\?q=(.*)', line)[0])\n gs = GoogleScholarCommon(url=re.findall(r'https://www.google.com/search\\?q=(.*)', line)[0])\n # gs = GoogleScholarCommon()\n gs.search_cite()\n","sub_path":"python/ijcai_spider/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"213845554","text":"import numpy as np\n\nfrom tensorpack.utils import viz\nfrom tensorpack.utils.palette import PALETTE_RGB\n\nfrom utils.np_box_ops import iou as np_iou\n\nfrom config import config as cfg\n\ndef draw_annotation(img, boxes,klass,is_crowd=None):\n labels=[]\n assert len(boxes)==len(klass)\n if is_crowd is not None:\n assert len(boxes)==len(is_crowd)\n for cls,crd in zip(klass,is_crowd):\n clsname=cFloatingPointError.DATA.CLASS_NAMES[cls]\n if crd==1:\n clsname+=';Crowd'\n labels.append(clsname)\n else:\n for cls in klass:\n labels.append(cfg.DATA.CLASS_NAMES[cls])\n img=viz.draw_boxes(img,boxes,labels)\n return img\n\ndef draw_proposal_recall(img,proposals,proposal_scores,gt_boxes):\n box_ious=np_iou(gt_boxes,proposals)\n box_ious_argsort=np.argsort(-box_ious,axis=1)\n good_proposals_ind=box_ious_argsort[:,:3]\n good_proposals_ind=np.unique(good_proposals_ind.ravel())\n\n proposals=proposals[good_proposals_ind,:]\n tags=list(map(str,proposal_scores[good_proposals_ind]))\n img=viz.draw_boxes(img,proposals,tags)\n return img, good_proposals_ind\n\ndef draw_predictions(img,boxes,scores):\n if len(boxes)==0:\n return img\n labels=scores.argmax(axis=1)\n scores=scores.max(axis=1)\n tags=[\"{},{:.2f}\".format(cfg.DATA.CLASS_NAMES[lb],score) for lb,score in zip(labels,scores)]\n return viz.draw_boxes(img,boxes,tags)\n\ndef draw_final_output(img,results):\n if len(results)==0:\n return img\n\n tags=[]\n for r in results:\n tags.append(\"{},{:.2f}\".format(cfg.DATA.CLASS_NAMES[r.class_id],r.score))\n boxes=np.asarray([r.box for r in results])\n ret=viz.draw_boxes(img,boxes,tags)\n\n for r in results:\n if r.mask is not None:\n ret=draw_mask(ret,r.mask)\n return ret\n\ndef draw_mask(im,mask,alpha=0.5,color=None):\n if color is None:\n color=PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]\n im=np.where(np.repeat((mask>0)[:,:,None],3,axis=2),im*(1-alpha)+color*alpha,im)\n im=im.astype('uint8')\n return im","sub_path":"Vision/Python/Applications/UnmannedCabinet/tensorpack/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"255093843","text":"\ndef meetscond(string):\n chars = set('\\'\\\".,')\n if len(string)<10 or len(string)>100 or any((c in chars) for c in string):\n return False\n return True\n\nlines = []\nwith open(\"mobile_nvp.txt\") as f:\n lines = f.read().splitlines()\n lines = map(lambda x: x.strip().split('\\t')[1], lines)\n lines = filter(meetscond, lines)\n \nwith open(\"dataset.txt\", \"w\") as f:\n for line in lines:\n f.write(line+\"\\n\") \n\n","sub_path":"Loggingapp/createds.py","file_name":"createds.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"439078033","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Philipp Temminghoff\n\"\"\"\n\nfrom qtpy import QtWidgets\n\nfrom prettyqt import widgets\n\n\nclass MenuBar(QtWidgets.QMenuBar):\n\n def add_action(self, action):\n self.addAction(action)\n\n\nif __name__ == \"__main__\":\n app = widgets.Application.create_default_app()\n win = QtWidgets.QMainWindow()\n menu_bar = MenuBar()\n win.setMenuBar(menu_bar)\n win.show()\n app.exec_()\n","sub_path":"prettyqt/widgets/menubar.py","file_name":"menubar.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"146267319","text":"# Andrew Piroli\n# MIT License\n#\n# Copyright (c) 2018-2020 AndrewPiroli\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport argparse\nimport sys\nimport logging\n\n\nclass IntTranslate:\n def __init__(self):\n self.config = []\n self.int_index = []\n self.old_int = []\n self.new_int = []\n self.stripped_map = {}\n logging.basicConfig(format=\"\", level=logging.DEBUG)\n self.log = logging.getLogger(\"IntTranslate\")\n self.log.setLevel(logging.CRITICAL)\n\n def discover(self):\n for idx, line in enumerate(self.config):\n if line.strip().startswith(\"interface \"):\n self.int_index.append(idx)\n self.log.debug(\n \"func discover(config): new interface discovered: \"\n + str(self.config[idx].strip())\n )\n self.log.debug(\n \"func discover(config): new interface discovered at idx: \"\n + str(idx)\n )\n\n def open_config(self):\n self.log.debug(\n \"func open_config(): attempting to open file at: \" + self.args.input\n )\n try:\n infile = open(self.args.input, \"r\")\n self.config = infile.readlines()\n infile.close()\n except Exception as e:\n self.log.critical(\"Error reading input file!\")\n self.log.critical(e)\n self.log.debug(\"error in open_config()\")\n self.log.debug(repr(e))\n self.log.debug(\"Configuration recieved successfully!\")\n self.log.debug(\"Dumping config to console:\")\n self.log.debug(self.config)\n self.log.debug(\"\")\n\n def save_config(self):\n self.log.debug(\n \"func save_config(): attempting save to file: \" + self.args.output\n )\n try:\n outfile = open(self.args.output, \"w+\", newline=\"\\n\")\n outfile.writelines(self.config)\n outfile.close()\n except Exception as e:\n self.log.critical(\"Error writing config\")\n self.log.critical(e)\n self.log.debug(\"error in save_config()\")\n self.log.debug(repr(e))\n\n def trans_config(self):\n self.log.debug(\"func trans_config(): stripped_map = \" + str(self.stripped_map))\n for idx in self.int_index:\n if self.config[idx].strip() in self.stripped_map:\n self.log.critical(\"Discovered interface inside existing map!\")\n self.log.critical(\n self.config[idx].strip()\n + \" -> \"\n + self.stripped_map.get(self.config[idx].strip())\n )\n self.config[idx] = (\n self.stripped_map.get(self.config[idx].strip()) + \"\\n\"\n )\n else:\n self.log.critical(\"New interface discovered!\")\n self.old_int.append(self.config[idx].strip())\n self.log.critical(self.config[idx].strip())\n answer = input(\n \"Enter new interface name or pass for passthru: interface \"\n ).strip()\n if answer.lower().startswith(\"pass\"):\n self.new_int.append(self.config[idx].strip())\n else:\n self.config[idx] = \"interface \" + answer + \"\\n\"\n self.new_int.append(\"interface \" + answer)\n self.log.debug(\"func trans_config(): old_int: \" + str(self.old_int))\n self.log.debug(\"func trans_config(): new_int: \" + str(self.new_int))\n\n def save_map(self):\n if self.args.reverse:\n self.log.critical(\"\")\n self.log.critical(\"Warning!\")\n self.log.critical(\"You have selected to reverse AND save the map!\")\n self.log.critical(\n \"Please confirm this is intended and the original map will not be overwritten\"\n )\n if input(\"Is this OK (y/N): \").strip().lower().startswith(\"y\"):\n self.log.critical(\"Saving map anyway!\")\n else:\n self.log.critical(\"Map save aborted!\")\n return\n self.log.debug(\n \"func save_map(): attempting to save map at file: \" + self.args.save\n )\n try:\n mapping = str(dict(zip(self.old_int, self.new_int)))\n mapfile = open(self.args.save, \"w+\", newline=\"\\n\")\n mapfile.write(mapping)\n mapfile.close()\n except Exception as e:\n self.log.critical(\"Error saving map file\")\n self.log.critical(e)\n self.log.debug(\"error in save_map()\")\n self.log.debug(repr(e))\n\n def load_map(self):\n self.stripped_map = None\n self.log.debug(\n \"func load_map() attempting to open map at file: \" + self.args.map\n )\n try:\n mapfile = open(self.args.map, \"r\")\n map = mapfile.read()\n self.log.debug(\"func load_map(): raw map text: \" + map)\n self.security_check(map)\n self.stripped_map = eval(map)\n except AssertionError as e:\n sys.exit(e)\n except Exception as e:\n self.log.critical(\"Error openening map\")\n self.log.critical(e)\n self.log.debug(\"Error in load_map()\")\n self.log.debug(repr(e))\n if not self.stripped_map:\n self.log.debug(\"func load_map(): error loading map\")\n return {}\n self.log.debug(\"func load_map(): stripped_map: \" + str(self.stripped_map))\n\n @staticmethod\n def int_array_fixup(map):\n old_int = map.keys()\n new_int = map.values()\n return [old_int, new_int]\n\n def security_check(\n self, mapfile,\n ): # Screen the map file because we will call eval() on it, try to prevent code injection by the user\n if any(\n [\n disallowed in mapfile\n for disallowed in [\n \"(\",\n \")\",\n \"import\",\n \"def\",\n \"if\",\n \"else\",\n \"catch\",\n \"=\",\n \"with\",\n \"as\",\n ]\n ]\n ):\n raise AssertionError(\n \"Security: Map file failed security check! The map file should only contain a python dictionary, NOT code.\"\n )\n else:\n self.log.debug(\"security_check(mapfile): Map pass security check.\")\n\n def main(self):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input\", help=\"Initial config file\")\n parser.add_argument(\"output\", help=\"Translated output config\")\n parser.add_argument(\n \"-d\", \"--debug\", help=\"Enable debuging to console\", action=\"store_true\"\n )\n parser.add_argument(\"-s\", \"--save\", help=\"Save mapping for future use\")\n parser.add_argument(\"-m\", \"--map\", help=\"Load existing map\")\n parser.add_argument(\n \"-r\", \"--reverse\", help=\"Reverse the translation map\", action=\"store_true\"\n )\n self.args = parser.parse_args()\n if self.args.debug:\n self.log.setLevel(logging.DEBUG)\n self.open_config()\n self.discover()\n if self.args.map:\n self.load_map()\n if self.args.reverse:\n if self.args.debug:\n self.log.critical(\"main: reversing loaded map file\")\n rev_map = {v: k for k, v in self.stripped_map.items()}\n self.stripped_map = rev_map\n fixup = self.int_array_fixup(self.stripped_map)\n self.old_int = list(fixup[0])\n self.new_int = list(fixup[1])\n fixup = None\n self.trans_config()\n self.save_config()\n if self.args.save:\n self.save_map()\n\n\nif __name__ == \"__main__\":\n IntTranslate().main()\n","sub_path":"interface_translator.py","file_name":"interface_translator.py","file_ext":"py","file_size_in_byte":8938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"381572949","text":"class Solution(object):\n def longestValidParentheses(self, s):\n if s == \"\":\n return 0\n size = len(s)\n dp = [0 for _ in range(size)]\n for i in range(1, size):\n if s[i] == \"(\":\n continue\n elif s[i] == \")\":\n if i -1 >= 0 and s[i-1] == \"(\":\n dp[i] = dp[i-2] + 2\n elif i - dp[i-1] -1 >= 0 and s[i-1] == \")\" and s[i - dp[i-1] -1] == \"(\":\n dp[i] = dp[i-1] + 2 + dp[i - dp[i-1] -2]\n return max(dp)\n\n def longestValidParentheses1(self, s):\n if s == \"\":\n return 0\n size = len(s)\n dp = [[0 for _ in range(size)] for _ in range(size)]\n for row in range(size):\n for col in range(row, size):\n if s[col] == \"(\":\n continue\n elif s[col] == \")\":\n if col - 1 >= 0 and s[col - 1] == \"(\": # 确保col - 1为正值\n dp[row][col] = dp[row][col -2] + 2\n elif col - dp[row][col - 1] - 1 >= 0 and s[col - 1] == \")\" and s[col - 1 - dp[row][col -1]] == \"(\":\n dp[row][col] = dp[row][col - 1] + 2 + dp[row][col - dp[row][col -1] - 2]\n return max(map(max, dp))\n\n def longestValidParentheses2(self, s):\n if s == \"\":\n return 0\n size = len(s)\n dp = [[0 for _ in range(size)] for _ in range(size)]\n for row in range(size):\n for col in range(row, size):\n if s[col] == \"(\":\n continue\n elif s[col] == \")\":\n valid_parenthese_len = dp[row][col - 1]\n if col - 1 >= 0 and s[col - 1] == \"(\": # 确保col - 1为正值\n dp[row][col] = dp[row][col - 2] + 2\n elif col - 1 - valid_parenthese_len >= 0 and s[col - 1] == \")\" and s[col - 1 - valid_parenthese_len] == \"(\":\n len_before_valid_parenthese = dp[row][col - 1 - valid_parenthese_len - 1]\n dp[row][col] = valid_parenthese_len + 2 + len_before_valid_parenthese\n return max(map(max, dp))\n\nprint(Solution().longestValidParentheses2(\"(())\"))","sub_path":"动态规划dp/32. 最长有效括号.py","file_name":"32. 最长有效括号.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"646208254","text":"# -*-coding:utf-8-*-\n# 提供数据库方法,与server搞定相关,修改时注意参数和返回值\n# 需要修改\n\nfrom sqlalchemy import func\nfrom sqlalchemy.dialects.mysql import pymysql\nfrom sqlalchemy.orm import DeclarativeMeta, session\nfrom sqlalchemy.sql import exists\nfrom sqlalchemy import Column, Integer, String, Enum, create_engine, ForeignKey, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.sql import text\nfrom sqlalchemy.sql.expression import select\nfrom do_with_DB.map import DbSharding\nfrom do_with_DB.Session import get_session\nfrom do_with_DB.createTable import Class_Students, User,Teacher,Student,RoleEnum,Class,Reports\n\nengine = create_engine('mysql+pymysql://root:nbuser@localhost:3306/OTH?charset=utf8', echo=True)\n'''数据库从删库到跑路'''\nclass DB_opera():\n def login_check(self,id,passward,role):#is ok\n session=get_session()\n id=int(id)\n passward=int(passward)\n legal= session.query(User).filter(User.ID ==id,User.pwsd==passward,User.Role==role).count()\n if legal ==1:\n print(\"ok\")\n session.close()\n return True\n session.close()\n return False\n\n def register(self,id, passward, role, name):\n session = get_session()\n #print('if work?')\n id = int(id)\n passward=int(passward)\n name=str(name)\n legal = session.query(User).filter(User.ID == id).count()\n print('legal is',legal)\n if legal <1:\n user_obj = User(ID=id, pwsd=int(passward), Role=role)\n session.add(user_obj)\n session.commit()\n if (role == \"teacher\"):\n teacher_obj = Teacher(ID=id, name=name)\n session.add(teacher_obj)\n session.commit()\n else:\n student_obj = Student(ID=id, name=name, roomID=id + 1)\n session.add(student_obj)\n session.commit()\n session.close()\n return True\n session.close()\n return False\n\n # def begin_class(self,class_id):#beging a class\n # session = get_session()\n # reports_obj = Reports(classID=class_id)\n # session.add(reports_obj)\n # session.commit()\n # \"\"\"建表\"\"\"\n # reportid=reports_obj.reportID#原来这样就可以获得新建项目的主键了吗\n # print('newID is',reportid)\n # create_report=Create.create_report(reportid)\n # create_report.metadata.create_all(engine)\n # session.close()\n # return True\n\n#新建课程,和Class交互,存老师id,课程id,课程名称\n def new_class(self,class_id, class_name, teacher_id):\n session = get_session()\n class_id=int(class_id)\n teacher_id=int(teacher_id)\n legal=session.query(Class).filter(Class.ClassID==class_id).count()\n print(legal)\n if legal<1:\n class_obj = Class(ClassID=class_id, Class_name=class_name, teacherID=teacher_id)\n session.add(class_obj)\n session.commit()\n session.close()\n return True\n #print(\"here?\")\n session.close()\n return False\n\n#不要dbmap\n#和CS表交互,数据库没问题\n#改方法\n#修改完成,且通过测试\n def join_class(self,class_id,student_id):\n student_id=int(student_id)\n session=get_session()\n join_obj=Class_Students(Class_ID=class_id,StudentID=student_id)\n session.add(join_obj)\n try:\n session.commit()\n except :\n print('该学生已经在课堂内了')\n session.close()\n\n#找老师教了什么课程,返回列表\n def find_teahcer_class(self,teacher_id):\n classlist=[]\n session=get_session()\n class_row=session.query(Class).filter(Class.teacherID==int(teacher_id))\n #寻找到多个结果,需要将其取出\n #for item in class_row:\n \n\n def sign_in_class(self,report_id,student_id):\n session=get_session()\n dbmap=DbSharding()\n report=dbmap.get_model(str(report_id))\n sign_obj=report(StudentID=int(student_id))\n session.add(sign_obj)\n session.commit()\n session.close()\n return True\n\n def end_class(self,report_id,student_id,grade_):\n session = get_session()\n dbmap = DbSharding()\n reportid = dbmap.get_model(str(report_id))\n update_row=session.query(reportid).filter(reportid.StudentID==int(student_id)).one()#!!!是这里 因为默认all()返回是一个队列\n if update_row:\n update_row.grade=int(grade_)\n session.add(update_row)\n session.commit()\n session.close()\n return True\n\n def show_sign_in(self,report_id):#test ok\n sign_in_list=[]\n session = get_session()\n dbmap = DbSharding()\n reportid = dbmap.get_model(str(report_id))\n list=session.query(reportid).all()\n for item in list:\n student_id=item.StudentID\n student=session.query(Student).filter(Student.ID==student_id).one()\n student_name=student.name\n sign_in_list.append((student_id,student_name))\n print(sign_in_list)\n session.close()\n return sign_in_list\n\n def query_history_student(self,student_id):#终于写好了 感觉写了好久 不太清醒了\n histroylist=[]\n session=get_session()\n all_report=session.query(Reports).all()#这是一个 行 的列表\n print(\"000000\", all_report)\n dbmap=DbSharding()\n for report in all_report:\n report_id=report.reportID#命名还是要给自己提示\n #print(\"!!!!!!!!!\",report_id)\n find_report=dbmap.get_model(str(report_id))\n #print(find_report)\n if not find_report:\n print(\"没有课\")\n if find_report!=False:\n falg=session.query(find_report).filter(find_report.StudentID==student_id).all()#这个flag没有用\n #print(\"????\",len(falg))\n print(falg,'how you work?')\n if falg:\n result=session.query(find_report).filter(find_report.StudentID==student_id).one()\n histroylist.append((report_id,result.grade))\n #print(histroylist)\n print(histroylist)\n session.close()\n return histroylist\n\n def query_history_teacher(self,class_id):\n result_list=[]\n session=get_session()\n report_list=session.query(Reports).filter(Reports.classID==int(class_id)).all()\n for report in report_list:\n result_list.append((report.reportID,class_id))\n session.close()\n print(result_list)\n return result_list#\n\n def check_namelist(self,class_id):\n namelist=[]\n session=get_session()\n namelist_=session.query(Class_Students).filter(Class_Students.Class_ID==class_id)\n for student in namelist_:\n student_id=student.StudentID\n studentname_=session.query(Student).filter(Student.ID==student_id).one()\n studentname=studentname_.name\n namelist.append((student_id,studentname))\n print(namelist)\n session.close()\n return namelist\n\n # dbmap=DbSharding()\n # theclass=dbmap.get_model(str(class_id))\n # row_name_list=session.query(theclass).all()\n # for item in row_name_list:\n # student_id=item.StudentID\n # student=session.query(Student).filter(Student.ID==student_id).all()\n # for item in student:\n # student_name=item.name\n # namelist.append((student_id,student_name))\n # print(namelist)\n # session.close()\n # return namelist\n\n def show_inform_teacher(self,teacher_id):\n list = []\n session=get_session()\n teachers_classes=session.query(Class).filter(Class.teacherID==int(teacher_id)).all()\n for item in teachers_classes:\n #第一个theclass是表的一列,下一行的class_name是从那一列中取出属性\n class_name=item.Class_name\n sum_=session.query(Class_Students).filter(Class_Students.Class_ID==item.ClassID).count()\n class_id=item.ClassID\n list.append((class_id,class_name,sum_))\n print(list)\n session.close()\n return list\n # list = []\n # session=get_session()\n # dbmap=DbSharding()\n # result_list=session.query(Class).filter(Class.teacherID==int(teacher_id)).all()\n # for item in result_list:\n # class_id=item.ClassID\n # class_name=item.Class_name\n # findlist=dbmap.get_model(str(class_id))\n # sum=session.query(findlist).count()\n # list.append((class_id,class_name,sum))\n # print(list)\n # session.close()\n # return list\n\n def show_brief_history_teacher(self,teacher_id):#md 意外的顺利啊\n #找到reports表里的所有reportid,按名字找到表,如果表里有studentid,加入元组\n list = []\n session = get_session()\n teachers_classes=session.query(Class).filter(Class.teacherID==int(teacher_id)).all()\n for item in teachers_classes:\n class_id=item.ClassID\n class_name=item.Class_name\n reports=session.query(Reports).filter(Reports.classID==item.ClassID).all()\n for report in reports:\n report_id=report.ReportID\n list.append((class_id, class_name, report_id))\n\n print(list) \n return list \n # list = []\n # session = get_session()\n # dbmap = DbSharding()\n # result_list = session.query(Class).filter(Class.teacherID == int(teacher_id)).all()\n # for item in result_list:\n # class_id = item.ClassID\n # class_name = item.Class_name\n # report_list=session.query(Reports).filter(Reports.classID==int(class_id)).all()\n # for i in report_list:\n # list.append((class_id,class_name,i.reportID))\n # print(list)\n # session.close()\n # return list\n\n def show_inform_student(self,student_id):\n list = []\n session=get_session()\n students_classes=session.query(Class_Students).filter(Class_Students.StudentID==int(student_id)).all()\n for item in students_classes:\n #第一个theclass是表的一列,下一行的class_name是从那一列中取出属性\n theclass=session.query(Class).filter(Class.ClassID==item.Class_ID).one()\n class_name=theclass.Class_name\n\n theteacher1=session.query(Class).filter(Class.ClassID==item.Class_ID).one()\n theteacher2=session.query(Teacher).filter(Teacher.ID==theteacher1.teacherID).one()\n teacher_name=theteacher2.name\n class_id=item.Class_ID\n\n list.append((class_id,class_name,teacher_name))\n print(list)\n session.close()\n return list\n \n # for item in all_class_list:\n # class_id=item.ClassID\n # i=dbmap.get_model(str(class_id)) #一个课程\n # if i:\n # n=session.query(i).filter(i.StudentID==student_id).all()\n # #如果课程表上有自己\n # if n:\n # the_class=session.query(Class).filter(Class.ClassID==int(class_id)).one()\n # class_name=the_class.Class_name\n # teacher=session.query(Teacher).filter(Teacher.ID==the_class.teacherID).one()\n # teacher_name=teacher.name\n # list.append((class_id,class_name,teacher_name))\n # print(list)\n # session.close()\n # return list\n\n def show_brief_history_student(self,student_id):\n #找到reports表里的所有reportid,按名字找到表,如果表里有studentid,加入元组\n list = []\n session = get_session()\n student_reports=session.query(Reports).filter(Reports.StudentID==student_id).all()\n for report in student_reports: \n class_id=report.classID\n mygrade=report.grade\n\n theclass=session.query(Class).filter(Class.ClassID==report.classID).one()\n class_name=theclass.Class_name\n\n list.append((class_id, class_name, mygrade))\n print(list) \n return list \n\n # dbmap = DbSharding()\n # all_report_list = session.query(Reports).all()\n # for item in all_report_list:\n # report_id = item.reportID\n # i = dbmap.get_model(str(report_id)) # 一个课程\n # if i:\n # n = session.query(i).filter(i.StudentID == student_id).all()\n # # 如果课程表上有自己\n # if n:\n # myreport=session.query(i).filter(i.StudentID == student_id).one()\n # mygrade=myreport.grade\n # myclass=session.query(Reports).filter(Reports.reportID==int(report_id)).one()\n # class_id=myclass.classID\n # find_class_name=session.query(Class).filter(Class.ClassID==class_id).one()\n # class_name = find_class_name.Class_name\n # list.append((class_id, class_name, mygrade))\n # print(list)\n # session.close()\n # return list\n\n\n#new_class(1001,\"english\",222)\n#new_class(1003,\"CS\",222)\n#new_reports(1000)\n#new_report(1000,101,99)\n\n\n#test=DB_opera()\n#test.register(102,121,\"student\",\"zhangsan\")\n#test.login_check(101,154,\"student\")\n#test.find_teahcer_class(987)\n# test.new_class(101,\"OOAD\",110001)\n# test.new_class(102,\"CS\",110001)\n# test.new_class(103,\"OS\",110001)\n# test.begin_class(101)\n# test.begin_class(102)\n# test.begin_class(103)\n#test.begin_class(500)\n#test.sign_in_class(1020,147)\n# test.end_class(6,2020100001,80)\n# test.end_class(5,2020100001,90)\n# test.end_class(4,2020100001,65)\n#test.begin_class(500)\n#test.sign_in_class(1009,101)\n#test.show_sign_in(1018)\n#test.query_history_student(147)\n#test.query_history_teacher(500)\n#test.check_namelist(453)\n#test.show_inform_teacher(987)\n#test.show_brief_history_teacher(987)\n#test.show_inform_student(2020100001)\n#test.show_brief_history_student(101)\n#test.begin_class(1344)\n# test.join_class(101,2020100001)\n# test.join_class(102,2020100001)\n# test.join_class(103,2020100001)\n# test.sign_in_class(4,2020100002)\n# test.sign_in_class(6,2020100002)\n\"\"\"\" 从1000初始化\nsession=get_session()\nreports_obj = Reports(reportID=1000,classID=1000)\nsession.add(reports_obj)\nsession.commit()\n\"\"\"\n'''\nsession = get_session()\nuser_obj = User(ID=101, pwsd=154, Role=RoleEnum.student)\nstudent_obj = Student(ID=101, name=\"zhangsan\", roomID=101)\nsession.add(user_obj)\nsession.commit()\nsession.add(student_obj)\nsession.commit()\n'''\n'''\nsession = get_session()\nreport_obj=Class(ClassID=1000,Class_name='math',teacherID=222)\nsession.add(report_obj)\nsession.commit()\n'''\n\n\n#register(1111,5555,\"teacher\",\"name1\")","sub_path":"Online_Teaching_Helper/do_with_DB/do_with_db.py","file_name":"do_with_db.py","file_ext":"py","file_size_in_byte":15059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"423729895","text":"import Cluster_Finder\nimport matplotlib.pyplot as plt\n\nrun_num = 'run3'\n\nn_frames = 100\n\nl_avg_hit_size_voltage = []\n\nl_voltage = []\n\nfor j in range(16):\n\n l_cluster = []\n l_hit_size = []\n l_avg_hit_size = []\n l_n_hit_pixels = []\n\n j = (j*0.02)+0.7\n l_voltage.append(j)\n\n run_voltage = str(j)+'v'\n if j == 1.0:\n run_voltage = '1v'\n\n run_name = run_num+'_'+run_voltage\n\n for i in range(n_frames): #1 to 100 inclusive\n i+=1\n\n filename = run_name+'_000' + str(i) + '.txt'\n\n if(i>=10):\n filename = run_name+'_00' + str(i) + '.txt'\n\n if(i>=100):\n filename = run_name+'_0' + str(i) + '.txt'\n\n filename = './Image_Intensifier_Testing/Voltage_Scan_Tests/' + run_num+ '/' + filename\n\n clusters,hit_size,n_hit_pixels,avg_hit_size = Cluster_Finder.c_find(filename)\n #print clusters, hit_size, avg_hit_size\n\n l_cluster.append(clusters)\n l_hit_size = l_hit_size + hit_size\n l_n_hit_pixels.append(n_hit_pixels)\n l_avg_hit_size.append(avg_hit_size)\n\n l_avg_hit_size_voltage.append(float(sum(l_hit_size))/float(len(l_hit_size)))\n\n\n\nfig = plt.figure(1,figsize=(8,6))\n\nif (run_num == 'run1'):\n fig.suptitle(run_name + 'Torch Off', fontsize=30)\n\nif (run_num == 'run2'):\n fig.suptitle(run_name + 'Torch On', fontsize=30)\n\n\nplt.subplot(111)\nplt.plot(l_voltage,l_avg_hit_size_voltage)\nplt.xlabel('Voltage')\nplt.ylabel('Avg. Cluster Size')\nplt.title('Average Cluster Size v. Voltage, Minimum Cluster Size > 0')\nplt.axis([0.7,1, 1.6, 3])\nplt.grid(True)\n\nplt.show()\n","sub_path":"Depricated Code/clustersize_v_voltage.py","file_name":"clustersize_v_voltage.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"324683158","text":"# Alexander Covington\n# 23 Oct 2015\n# HW 1a\n# This program takes a series of user inputs (initial population, rate of growth, total hours, and the hours it\n# it takes to achieve that growth rate) and inputs them into a formula to predict the growth of a population of\n# butterflies. It then prints that final value.\n\np = int(input(\"Enter the initial population: \"))\nr = int(input(\"Enter the rate: \"))\ntr = int(input(\"Enter the number of hours to achieve the rate of growth: \"))\nt = int(input(\"Enter the total hours: \"))\nfinal = int(p * (r)**(t / tr))\n\nprint(\"The total population is\", final)\n","sub_path":"labs/covington_alexander_hw1a.py","file_name":"covington_alexander_hw1a.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"517498885","text":"import mla\nimport csv\n\n\nTrainFile = open(\"train.csv\", \"r\")\n\nTrainingData = []\nReading = csv.reader(TrainFile)\nfor row in Reading:\n TrainingData.append(row)\n\nfor i in range(len(TrainingData) - 1):\n TrainingData[i+1][0] = int(TrainingData[i+1][0])\n for j in range(len(TrainingData[0]) - 1):\n TrainingData[i+1][j+1] = int(TrainingData[i+1][j+1]) / 255\n\n\nNL = [len(TrainingData[1]) - 1, int((len(TrainingData[1]) - 1) / 1.5), int((len(TrainingData[1]) - 1)/2.5), 10]\nLR = 0.1\nL = len(NL)\n\nnn = mla.neuralnetwork(NL, LR, L)\nnn.LoadWeight(\"new_a.npy\")\n\nright = 0\nwrong = 0\n\nfor i in range(len(TrainingData) - 1):\n\toutput = nn.query(TrainingData[i + 1][1:])\n\toutput_index = 0\n\tfor j in range(10):\n\t\tif (output[j] > output[output_index]):\n\t\t\toutput_index = j\n\tif output_index == TrainingData[i + 1][0]:\n\t\tright += 1\n\t\t#print(\"#\", i+1, \" correct!\")\n\telse:\n\t\twrong += 1\n\t\t#print(\"#\", i+1, \" wrong!\")\n\t#print(\"R: \", right, \"\tW: \", wrong)\nprint(\"\\n\\nRate: \", right / (right + wrong))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"119585390","text":"import time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_MCP3008\nfrom mpu6050 import mpu6050\nfrom time import sleep\nimport wiringpi\nimport RPi.GPIO as GPIO\nimport random\n\n\nCLK = 18\nMISO = 24\nMOSI = 25\nCS = 21\nmcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)\nFIRE_CHANNEL = 5\nMICROPHONE_CHANNEL = 4\nDISTANCE_SENSOR_CHANNEL = 3\nPOTENTIOMETER_CHANNEL = 2\n\n# Hardware SPI configuration:\n# SPI_PORT = 0\n# SPI_DEVICE = 0\n# mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))\n\n# set mode\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\n# declare variables\n\ngpioPin_led_blue = 20\ngpioPin_led_red = 16\ngpioPin_led_yellow = 12\ngpioPin_led_green = 23\ngpioPin_speaker = 19\n\nfrequencies = {\n gpioPin_led_blue: 784,\n gpioPin_led_green: 659,\n gpioPin_led_yellow: 523,\n gpioPin_led_red: 440,\n}\n\nleds = [gpioPin_led_green, gpioPin_led_yellow, gpioPin_led_blue, gpioPin_led_red]\n\ngame_is_on = True\n\n# initiate pins\nGPIO.setup(gpioPin_led_red, GPIO.OUT, initial=GPIO.LOW)\nGPIO.setup(gpioPin_led_green, GPIO.OUT, initial=GPIO.LOW)\nGPIO.setup(gpioPin_led_yellow, GPIO.OUT, initial=GPIO.LOW)\nGPIO.setup(gpioPin_led_blue, GPIO.OUT, initial=GPIO.LOW)\n\nwiringpi.wiringPiSetupGpio()\nwiringpi.softToneCreate(gpioPin_speaker)\n\nindex = 0\ncurrent_num_of_moves = 1\ncomputer_moves = []\n\n\ndef activate_led(pin_num, freq):\n GPIO.output(pin_num, GPIO.HIGH)\n wiringpi.softToneWrite(gpioPin_speaker, freq)\n sleep(0.5)\n GPIO.output(pin_num, GPIO.LOW)\n wiringpi.softToneWrite(gpioPin_speaker, 0)\n\n\ndef get_random_led_and_freq():\n global frequencies, leds\n led = random.choice(leds)\n freq = frequencies[led]\n return led, freq\n\n\ndef computer_turn():\n global computer_moves, index, frequencies, current_num_of_moves\n index = 0\n add_move_to_computer()\n for i in range(current_num_of_moves):\n activate_led(computer_moves[i], frequencies[computer_moves[i]])\n sleep(1)\n\n\ndef add_move_to_computer():\n global computer_moves, frequencies\n led, freq = get_random_led_and_freq()\n computer_moves.append(led)\n\n\ndef end_game():\n global game_is_on, computer_moves, leds\n computer_moves = []\n wiringpi.softToneWrite(gpioPin_speaker, 900)\n for led in leds:\n GPIO.output(led, GPIO.HIGH)\n sleep(3)\n\n\nprint('Reading MCP3008 values, press Ctrl-C to quit...')\n# Print nice channel column headers.\nprint('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8)))\nprint('-' * 57)\n# Main program loop.\nreadAgain = True\nwhile game_is_on:\n global index, current_num_of_moves, computer_moves\n computer_turn()\n while index < current_num_of_moves:\n # Read all the ADC channel values in a list.\n values = [0]*8\n for i in range(8):\n # The read_adc function will get the value of the specified channel (0-7).\n values[i] = mcp.read_adc(i)\n if readAgain and i is MICROPHONE_CHANNEL:\n last_microphone_sample = values[MICROPHONE_CHANNEL]\n readAgain = False\n if values[FIRE_CHANNEL] < 100 and i is FIRE_CHANNEL:\n if gpioPin_led_green == computer_moves[index]:\n index += 1\n activate_led(gpioPin_led_green,frequencies[gpioPin_led_green])\n else:\n end_game()\n elif i is MICROPHONE_CHANNEL and abs(values[MICROPHONE_CHANNEL] - last_microphone_sample) > 100:\n if gpioPin_led_red == computer_moves[index]:\n index += 1\n activate_led(gpioPin_led_red, frequencies[gpioPin_led_red])\n readAgain = True\n else:\n end_game()\n elif values[DISTANCE_SENSOR_CHANNEL] < 100 and i is DISTANCE_SENSOR_CHANNEL:\n if gpioPin_led_yellow == computer_moves[index]:\n index += 1\n activate_led(gpioPin_led_yellow, frequencies[gpioPin_led_yellow])\n else:\n end_game()\n elif values[POTENTIOMETER_CHANNEL] == 0 and i is POTENTIOMETER_CHANNEL:\n if gpioPin_led_blue == computer_moves[index]:\n index += 1\n activate_led(gpioPin_led_blue, frequencies[gpioPin_led_blue])\n else:\n end_game()\n\n # Print the ADC values.\n print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))\n # Pause for half a second.\n time.sleep(0.5)\n current_num_of_moves += 1\n sleep(2)\n\n\n","sub_path":"IOT/simon-sensors-game/simonSensingGame.py","file_name":"simonSensingGame.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"270302211","text":"import cv2\nimport numpy as np\n# from IPython import display\nfrom matplotlib import pyplot as plt\nimport datetime\nimport os\nimport time\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore, storage\nimport subprocess\n\nfrom PIL import Image, ImageFilter\n\ndef find_cont(img_before, img_after):\n fgbg = cv2.createBackgroundSubtractorMOG2()\n\n fgmask = fgbg.apply(img_before)\n fgmask = fgbg.apply(img_after)\n #im_diff = img_before - img_after\n # print(im_diff)\n #fgmask = np.abs(im_diff)\n # cv2.imshow(\"bin_img\", fgmask)\n # cv2.waitKey(0)\n # fgmask = np.abs(im_diff)\n # cv2.imwrite(\"fgmask.png\",fgmask)\n # fgmask = cv2.cvtColor(fgmask, cv2.COLOR_BGR2GRAY)\n\n # グレースケール化\n #gray = cv2.cvtColor(fgmask, cv2.COLOR_BGR2GRAY)\n\n _, img_bin = cv2.threshold(fgmask, 0, 255, cv2.THRESH_OTSU)\n kernel = np.ones((5, 5), np.uint8)\n img_bin = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernel)\n # cv2.imshow(\"bin_img\",bin_img)\n # cv2.waitKey(0)\n cv2.imwrite(\"img_bin.png\",img_bin)\n\n\n # 輪郭抽出\n tmp_contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n return tmp_contours\n\ndef result_img(count_gomi):\n img_list = [Image.open('gomi_{}.png'.format(i+1)) for i in range(count_gomi)]\n # print(img_list)\n img_width = [i.size[0] for i in img_list]\n img_height = [i.size[1] for i in img_list]\n\n img_height_result = max(img_height)+200\n img_width_result = sum(img_width)+100*count_gomi+100\n\n\n bg = Image.new(\"RGBA\", (img_width_result, img_height_result), (255, 255, 255, 0))\n\n tmp_width = 0\n for i, im in enumerate(img_list):\n bg.paste(im, (int(100+tmp_width), int((img_height_result-im.size[1])/2)))\n tmp_width = tmp_width + im.size[0] + 100\n\n bg.save(\"result_img.png\")\n\nif __name__ == '__main__':\n cred = credentials.Certificate(\n \"gikucamp-firebase-adminsdk-bw43u-3c588aa9ee.json\")\n firebase_admin.initialize_app(cred, {'storageBucket': 'gikucamp.appspot.com'})\n db = firestore.client()\n doc_ref = db.collection(u'data').document(u'90TwVL13wTuPpmCgw24C')\n ref = db.collection(u'data')\n docs = ref.stream()\n bucket = storage.bucket()\n #filename = 'outline.png'\n #blob = bucket.blob(filename)\n content_type = 'outline/png'\n\n #filename2 = 'img_gomi.png'\n filename2 = 'img_gomi.png'\n blob = bucket.blob(filename2)\n\n\n area_total_previous = 0\n area_total = 0\n count_gomi = 0\n hp_max = 0\n count_gomi = 0\n\n camera = cv2.VideoCapture(0)\n for i in range(1, 600):\n # if area_total > hp_max:\n # hp_max = area_total\n ret, frame = camera.read()\n if ret:\n print('Success')\n cv2.imwrite('final{}.png'.format(i), frame)\n\n else:\n print('Failed')\n\n # start_name = 'final{}.png'.format(i-1)\n # final_name = 'final{}.png'.format(i)\n img_before = cv2.imread('final{}.png'.format(i-1))\n img_after = cv2.imread('final{}.png'.format(i))\n\n cont_n = find_cont(img_before, img_after)\n #print(\"contours\", contours)\n\n # 輪郭を描写\n img_outline = img_after.copy()\n cv2.drawContours(img_outline, cont_n, -1, color=(0, 255, 0), thickness=5)\n cv2.imwrite('outline.png', img_outline)\n\n # for i in cont_n:\n # print(cv2.contourArea(i))\n\n # 小さい輪郭を削除\n cont_A = list(filter(lambda x: cv2.contourArea(x) > 20000, cont_n))\n # print(\"contours-\", cont_n)\n\n # 輪郭を描写\n # img_outline = img2.copy()\n cv2.drawContours(img_outline, cont_A, -1, color=(0, 255, 0), thickness=5)\n cv2.imwrite('outline_.png', img_outline)\n final_area = 0\n # cv2.imshow(\"img_outline\",img_after)\n # cv2.waitKey()\n\n # トータルエリアを計算\n\n img_0 = cv2.imread('final0.png')\n cont_0 = find_cont(img_0, img_after)\n cont_0A = list(filter(lambda x: cv2.contourArea(x) > 10000, cont_0))\n\n area_total_previous = area_total\n area_total = sum([cv2.contourArea(i) for i in cont_0A])\n\n for a in range(len(cont_A)):\n area = cv2.contourArea(cont_A[a])\n print(a, area)\n final_area = final_area + area\n\n\n print(\"final_area\", final_area)\n print(\"area_total\", area_total)\n print(\"area_total_previous\", area_total_previous)\n\n final_area = area_total\n\n\n\n try:\n if area_total < area_total_previous:\n count_gomi = count_gomi+1\n # 外形のマスク画像を生成\n mask = np.zeros_like(img_before[:, :, 0])\n cv2.drawContours(mask, [cont_A[0]], -1, color=255, thickness=-1)\n #if(area_diff>0):\n ch_b, ch_g, ch_r = cv2.split(img_before[:, :, :3])\n img_alpha = cv2.merge((ch_b, ch_g, ch_r, mask))\n cv2.imwrite(\"img_alpha.png\", img_alpha)\n\n # 外枠の矩形を計算\n x, y, w, h = cv2.boundingRect(cont_A[0])\n img_gomi = img_alpha[y:y + h, x:x + w]\n cv2.imwrite(\"img_gomi.png\", img_gomi)\n\n # 現在取ったものの画像をfirebaseに送信\n\n with open(filename2, 'rb') as f:\n blob.upload_from_file(f, content_type=content_type)\n\n gomi_path ='gomi_{}.png'.format(count_gomi)\n cv2.imwrite(gomi_path, img_gomi)\n\n blob_gomi_path = bucket.blob(gomi_path)\n with open(gomi_path, 'rb') as f:\n blob_gomi_path.upload_from_file(f, content_type=content_type)\n\n\n\n except IndexError:\n print('Not found: gomi')\n\n # firebaseにトータルの面積を送信\n for doc in docs:\n print(u'{} => {}'.format(doc.id, doc.to_dict()))\n\n if final_area > hp_max:\n hp_max = area_total\n\n doc_ref.set({\n u'amount': f\"{final_area}\",\n u'count_gomi': f\"{count_gomi}\",\n u'hp_max': f\"{hp_max}\",\n u'hp_diff': f\"{area_total - area_total_previous}\",\n\n })\n if area_total == 0:\n result_path = \"result_img.png\"\n result_img(count_gomi)\n blob_result_path = bucket.blob(result_path)\n with open(result_path, 'rb') as f:\n blob_result_path.upload_from_file(f, content_type=content_type)\n\n hp_max = 0\n count_gomi = 0\n\n\n print(\"今置け!\")\n #cv2.waitKey(0)\n #input()\n #subprocess.call('PAUSE', shell=True)\n var = input(\"Please input variable : \")\n print(\"Input variable is : {}\".format(var))\n\n\n ''' \n img_gomiは現在取った物のだけの輪郭を取った画像\n start_name = start.png\n final_name = final.png\n img = final.png\n img2 = result.png\n result.pngはグレースケール画像\n img2に輪郭を描写したのがoutline.png\n '''\n","sub_path":"execute_no3.py","file_name":"execute_no3.py","file_ext":"py","file_size_in_byte":7041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"267864403","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef sum_hourglass(a, i, j):\n Sum = a[i][j] + a[i][j + 1] + a[i][j + 2]\n i += 1\n Sum += a[i][j + 1]\n i += 1\n Sum += a[i][j] + a[i][j + 1] + a[i][j + 2]\n return Sum\n\ndef max_hourglass(a):\n Max = -9 * 100\n for i in range(0, 4):\n for j in range(0, 4):\n Sum = sum_hourglass(a, i, j)\n if Sum > Max:\n Max = Sum\n return Max\n\narr = []\nfor _ in range(6):\n arr.append(list(map(int, input().rstrip().split())))\n\nprint(max_hourglass(arr))","sub_path":"Day 11 2D Arrays.py","file_name":"Day 11 2D Arrays.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"132256790","text":"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport scipy.io.wavfile\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport scipy\r\nimport scipy.signal\r\n\r\n\r\nbitrate, data = scipy.io.wavfile.read('Windows Logon.wav')\r\n\r\nxbeg = 33000\r\nxend = xbeg + bitrate * 0.1\r\nx = data.T[0][int(xbeg):int(xend)]\r\n\r\n#####\r\n\r\nplt.plot(x)\r\n\r\n#####\r\n\r\nplt.figure()\r\ncount, bins, ignored = plt.hist(x, 15, density=True)\r\n\r\n#####\r\n\r\nN = x.size\r\nX = scipy.fft(x)\r\nXdb = 20*scipy.log10(scipy.absolute(X))\r\nf = scipy.linspace(0, bitrate, N, endpoint=False)\r\n\r\nplt.figure()\r\nplt.plot(f, Xdb)\r\n\r\n#####\r\n\r\nspec = np.fft.fft(x)\r\nfreq = np.fft.fftfreq(x.size, d=1/bitrate)\r\n\r\nplt.figure()\r\nplt.plot(freq, spec)\r\n#plt.xlim(0, 1000)\r\n#plt.xscale('log')\r\n#plt.yscale('log')\r\n\r\nplt.figure()\r\nplt.plot(freq, np.abs(spec))\r\n#plt.xlim(0, 10000)\r\nplt.xscale('log')\r\nplt.yscale('log')\r\n\r\n#####\r\n\r\nf, Pxx_den = scipy.signal.welch(x, bitrate*2, nperseg=75)\r\n\r\nplt.figure()\r\nplt.semilogy(f, Pxx_den)\r\nplt.plot(f, np.ones_like(f))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"soundmax/!dump/soundmax_0.3.py","file_name":"soundmax_0.3.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"546496755","text":"import sys\nimport math\nimport random\n\n\n#if(len(sys.argv) <= 1):\n #print 'Error! What is the csv file to parse? First line must be the fields names'\n #exit(1)\n\nnumrotations = 100\ndelta = math.pi/8.0\nf = open('./data', 'w')\n\n#f.write('0;0\\n')\n#f.write('1;0\\n')\n#f.write('0;1\\n')\n#f.write('1;1\\n')\ncount=0\n\nradius = 0.1\nfor i in range(0, numrotations):\n j = 0\n while(j < 2.0 * math.pi):\n x = random.uniform(0.1,0.2) * math.cos(j)\n y = random.uniform(0.1,0.2) * math.sin(j)\n\n f.write(str(x)+';'+str(y)+'\\n')\n count+=1\n\n j+=delta\n\nnumrotations = 5\nradius = 0.5\ndelta = math.pi/32.0\nfor i in range(0, 2*numrotations):\n j = 0\n while(j < 2.0 * math.pi):\n x = random.uniform(0.5,1.0) * math.cos(j)\n y = random.uniform(0.5,1.0) * math.sin(j)\n\n f.write(str(x)+';'+str(y)+'\\n')\n count+=1\n\n j+=delta\n\nf.close()\n\ninfo = open('./info.txt', 'w')\ninfo.write('numentries: '+str(count)+'\\n')\n#info.write('numdim: '+str(numdim)+'\\n')\ninfo.write('numdim: 2\\n')\ninfo.write('min: 0\\n')\ninfo.write('max: 1\\n')\ninfo.write('isline: 0\\n')\ninfo.write('hasgeoinfo: 0\\n')\ninfo.close()","sub_path":"data/synt1/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"369707891","text":"#imports\n#essentials\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport tensorflow as tf\n\n#pycuda\nfrom pycuda import gpuarray\nimport pycuda.driver as cuda\nfrom pycuda.compiler import SourceModule\nimport pycuda.autoinit\n\n#sklearn\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split, GridSearchCV, validation_curve\n\n\"\"\"Import MNIST Data\"\"\"\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=False)\n\nX_train = mnist.train.images\nX_test = mnist.test.images\ny_train = mnist.train.labels\ny_test = mnist.test.labels\n\nX_train = np.float32(X_train)\nX_test = np.float32(X_test)\ny_train = np.int32(y_train)\ny_test = np.int32(y_test)\n\nclass GradientDescent:\n\t\"\"\"\n\tImplementation of SGD with:\n\t\t-fixed step size\n\t\t-no early stopping\n\t\t-logistic regression for MNIST data\n\n\tFour Modes:\n\t\t-algorithmic\n\t\t-batch\n\t\t-multiclass\n\t\t-Hogwild!\n\t\"\"\"\n\n\tsgd_batch_kernel_code = \"\"\"\n\t\t#include \n\t\t#include \n\t\t__global__ void SGD_batch(float *X_train, int *y_train, float *weights, float *output, float eta, int rows)\n\t\t{\n\n\t\t//initialize -------------\n\t\t//tx between 0 and 32\n\t\t//ty between 0 and 10\n\t\tint tx = threadIdx.x;\n\t\tint ty = threadIdx.y; \n\t\tconst int data_rows = rows;\n\t\tconst int data_dimension = 784;\n\t\tfloat e = 2.718281828459;\n\n\t\t//put weights in shared memory ----------\n\t\t__shared__ float weight_shared[10][data_dimension];\n\t\t__shared__ float coefficients[10][32]; \n\n\t\tfor (int i=0; i t0:\n I_spd2[ii] = I_0*np.exp(-(_pt-t0)/tau_minus)\n\n#%% load wr\nif compare_to_wr == True:\n \n directory = 'wrspice_data'\n file_name = 'syn_0jj.dat'\n data_dict = read_wr_data(directory+'/'+file_name)\n \n time_vec_wr = data_dict['time']\n initial_ind = (np.abs(time_vec_wr-1.0e-9)).argmin()\n time_vec_wr = time_vec_wr[initial_ind:]-time_vec_wr[initial_ind]\n I_spd2_wr = data_dict['L0#branch']\n I_spd2_wr = I_spd2_wr[initial_ind:]\n \n actual_data = np.vstack((time_vec[:],I_spd2[:]))\n target_data = np.vstack((time_vec_wr[:],I_spd2_wr[:]))\n \n error = chi_squared_error(target_data,actual_data)\n# error = 1\n\n#%% plot\n\nfig = plt.figure()\nif compare_to_wr == False:\n plt.title('r_spd2 = {}'.format(r_spd2)) \nelse:\n plt.title('error = {:6.4e}; r_spd2 = {}'.format(error, r_spd2)) \nax = fig.gca()\n\ncolor_list = [colors['blue3'],colors['red3'],colors['green3'],colors['yellow3']]\nax.plot(time_vec*1e9,I_spd2*1e6, '-', color = colors['blue3'] , label = 'analytical') #\nif compare_to_wr == True:\n ax.plot(time_vec_wr*1e9,I_spd2_wr*1e6, '-', color = colors['red3'] , label = 'spice') #\n\nax.set_xlabel(r'Time [ns]')\nax.set_ylabel(r'$I_{spd2}$ [$\\mu$A]')\n\nax.legend()\n# ax.grid(True,which='both')\n\nplt.show()\n","sub_path":"synapse/s__syn__spd_response__flux_drive_version.py","file_name":"s__syn__spd_response__flux_drive_version.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"421217102","text":"class Main:\n \n def __init__(self):\n \n \n self.MAX_SEQUENCE_LENGTH = 300\n self.MAX_NUM_WORDS = 60000\n self.EMBEDDING_DIM = 300\n self.VALIDATION_SPLIT = 0.2\n \n stances = pd.read_csv(\"train_stances.csv\")\n bodies = pd.read_csv(\"train_bodies.csv\")\n \n dataset = pd.merge(stances, bodies)\n \n dataset = dataset.drop(['BodyID'], axis=1)\n \n cols = dataset.columns.tolist()\n cols = cols[-1:] + cols[:-1]\n dataset = dataset[cols]\n \n y = dataset['Stance']\n y = np.array(y)\n \n \n self.labelencoder_y = LabelEncoder()\n y = self.labelencoder_y.fit_transform(y)\n \n \n \n self.tokenizer = Tokenizer(nb_words=self.MAX_NUM_WORDS)\n self.tokenizer.fit_on_texts(dataset['Headline']+dataset['articleBody'])\n \n self.model = keras.models.load_model('model') \n \n def test(self,tweet,articles):\n warnings.filterwarnings(action='ignore', category=DeprecationWarning)\n from keras.preprocessing.sequence import pad_sequences\n sequences1 = self.tokenizer.texts_to_sequences([tweet])\n test1 = pad_sequences(sequences1, maxlen=self.MAX_SEQUENCE_LENGTH) \n credibility_score=0\n print('Mic Check')\n print('len of Articles : ',len(articles))\n \n for article in articles:\n sequences2 = self.tokenizer.texts_to_sequences([article])\n test2 = pad_sequences(sequences2, maxlen=self.MAX_SEQUENCE_LENGTH)\n y_pred = self.model.predict([test1, test2])\n y_pred[y_pred > 0.5] = 1\n y_pred[y_pred < 0.5] = 0\n y_pred_num = np.argmax(y_pred)\n stance = self.labelencoder_y.inverse_transform(y_pred_num)\n if stance == \"agree\":\n credibility_score+=1\n elif stance == \"disagree\":\n credibility_score-=1\n elif stance == \"discuss\":\n credibility_score+=0.25\n else:\n credibility_score+=0\n print('\\n\\nY pred:',stance)\n print('\\n\\n Credibility Score:',(credibility_score/len(articles)*100))\n return credibility_score\n","sub_path":"App/stance.py","file_name":"stance.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"637579299","text":"import sys\nimport os\nimport subprocess\nimport re\nimport time\n\nimport ioparse as iop \nimport strlist as strl \nimport cmdline as cml \n#import cmdutil as cmu\nimport mathops as mops\n\n\nclass isov(object):\n\n def __init__(self, initialize = True, kernel = 'linux'):\n\n # Constants\n self.s4 = \" \"\n\n # File and folder names\n\n self.INITIAL_DIR = 'ISOV'\n self.INITIAL_PATH = ''\n\n self.PAR_FILE_NAME = 'par.don'\n self.VAL_FILE_NAME = 'nucleus.don'\n\n self.SRCFILE = 'src'\n self.srcpath = ''\n\n self.BINFILE = 'bin'\n self.binpath = ''\n\n self.DATFILE = 'dat'\n self.datpath = ''\n\n self.EOSDIR = 'eos'\n self.eospath = ''\n\n self.PARFILE = 'parameters.don'\n self.parpath = ''\n\n self.options = 'options.don'\n self.optpath = ''\n\n self.OPTPARS = 'opt_par.etr'\n self.SKINVAL = 'skin.srt'\n\n # Regex codes\n DIGIT = \"(\\d+)\"\n DIGITSPC = DIGIT+\"\\s+\"\n FLOATER = \"(\\d+.+\\d*)\\s*\"\n\n # Compiling regex code\n# self.AZPAIRS = re.compile(\"\\s*AZpairs\\s*:\\s*([T,F,t,f]\\D+)\")\n\n self.PAIRS = re.compile(\"\\s*(\\d+),(\\d+)\")\n self.LOOPS = re.compile(\"\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\")\n self.PARCM = re.compile(\"\\s*\"+9*DIGITSPC+FLOATER+DIGIT)\n self.PARGP = re.compile(\"\\s*\"+5*DIGITSPC+FLOATER+DIGIT)\n\n # debug-----------------\n self.time_Start = time.time()\n\n # Initialization\n self.INITIALIZATION = False\n\n # Initial Pathway Errors\n self.PARSFILE_PATH_ERROR = False\n self.SKVLFILE_PATH_ERROR = False\n self.EOSDIR_PATH_ERROR = False\n self.BINDIR_PATH_ERROR = False\n\n # Set Pathways\n\n self.INTERNAL_CML_SET = False\n self.PARSFILE_PATH_SET = False\n self.SKVLFILE_PATH_SET = False \n self.EOSDIR_PATH_SET = False \n self.BINDIR_PATH_SET = False \n self.SUBPROCESS_PATH_SET = False\n self.INITIAL_PAR_SET = False\n\n # Other intial task errors\n self.INTERNAL_CML_ERROR = False\n self.SUBPROCESS_PATH_ERROR = False\n self.PAR_FORMAT_ERROR = False\n\n # Skval errors\n self.SKVAL_FORMAT_ERROR = False \n self.SKVAL_CONTROL_ERROR = False\n\n # EoS errors \n self.EOS_SPLIT_FILE_ERROR = False\n self.EOS_FILE_FORMAT_ERROR = False \n self.EOS_SPLIT_PARSE_ERROR = False\n self.EOS_PASS_ERROR = False\n self.INITIAL_PARS_ERROR = False\n\n # Execution Errors\n self.EXIT_ERROR = False\n\n # BENV objects and variables---------------|\n \n # initial data \n self.initial_pars = ''\n self.initial_a = 0\n self.initial_z = 0 \n\n # skval functionality\n self.incloop = False \n self.azpairs = False\n self.mirrors = False \n self.initpar = False\n self.eospars = False \n self.eosgrup = False\n\n # internal shell command line\n self.cmv = object() \n self.cmvutil = object()\n\n # variables\n self.run_time = 0\n\n #initialization (optional) \n if(initialize):\n self.INITIALIZATION = True\n\n print(\" \")\n print(\"Initialization option detected\")\n print(\"Error messages and test results shown below\")\n print(\"Initialization sequence will now begin...\\n\")\n\n try:\n self.cmv = cml.PathParse(kernel)\n# self.cmvutil = cmu.cmdUtil(self.cmv)\n self.INITIAL_PATH = self.cmv.varPath\n self.INTERNAL_CML_SET = True\n except:\n print(\"[benv] Error: internal shell command object 'cmv' could not be created\\n\")\n self.INTERNAL_CML_ERROR = True\n\n self.set_par_path()\n self.set_skvl_path()\n self.set_eos_path()\n self.set_bin_dir()\n\n if(self.PARSFILE_PATH_ERROR):\n print(\"[benv] Error: no path found for the 'PARSFILE' file\")\n print(\"No attempt will be made to get values from 'PARSFILE'\\n\")\n else:\n self.initial_pars, self.initial_vals = self.data_from_pars()\n if((self.initial_pars, self.initial_vals) == ('','')):\n print(\"[benv] Error: 'PARSFILE' file contains invalid formatting\\n\")\n self.PAR_FORMAT_ERROR = True\n else:\n self.initial_pars = self.initial_pars[0]\n\n try: \n self.initial_a, self.initial_z = strl.str_to_list(self.initial_vals[-1], filtre=True) \n self.initial_a = int(float(strl.str_clean(self.initial_a)))\n self.initial_z = int(float(strl.str_clean(self.initial_z))) \n self.INITIAL_PAR_SET = True \n except:\n print(\"[benv] Error: failure to parse isotope values A and Z to integers (the last parameter line)\\n\")\n self.PAR_FORMAT_ERROR = True\n \n self.assess_initialization() \n print(\"Initialization sequence complete.\\n\")\n if(self.EXIT_ERROR):\n print(\"A fatal error was detected in the initialization sequence...the script will now terminate\\n\")\n self.exit_function(\"during initalization...see E-level error checks for details\") \n else: \n print(\"Runtime warnings and errors printed below: \\n\")\n \n def exit_function(self, action_msg, failure=True):\n if(failure):\n print(\"ExitError: 'BENV' failed \"+action_msg)\n print(\"Run Number upon exit: \"+str(self.run_time))\n print(\"Script run-time : \"+str(time.time()-self.time_Start))\n print(\" \")\n sys.exit()\n","sub_path":"script_applications/isov_scripts/isov.py","file_name":"isov.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"446313297","text":"from pygame import event, KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT, K_ESCAPE, key, mouse\r\nfrom pygame import KMOD_CTRL, KMOD_SHIFT, K_RETURN, K_s, K_d, K_c, K_a, K_F3, Rect\r\nfrom backend import salir, EventHandler, System, Selected\r\nfrom backend.group import WidgetGroup\r\n\r\n\r\nclass WidgetHandler:\r\n widgets = WidgetGroup()\r\n active_widget = None\r\n name = \"WidgetHandler\"\r\n selection = None\r\n on_selection = False\r\n selected = Selected()\r\n numerable = []\r\n active_area = Rect(0, 21, 537, 363)\r\n\r\n @classmethod\r\n def add_widget(cls, widget):\r\n cls.widgets.add(widget)\r\n if widget.numerable:\r\n cls.numerable.append(widget)\r\n System.number_of_nodes += 1\r\n\r\n @classmethod\r\n def del_widget(cls, widget):\r\n cls.widgets.remove(widget)\r\n if widget.numerable:\r\n cls.numerable.remove(widget)\r\n System.number_of_nodes -= 1\r\n\r\n cls.numerable.sort(key=lambda o: o.idx)\r\n\r\n @classmethod\r\n def set_active(cls, widget):\r\n cls.active_widget = widget\r\n\r\n @classmethod\r\n def enable_selection(cls, selection_object):\r\n cls.selection = selection_object\r\n cls.add_widget(selection_object)\r\n cls.on_selection = True\r\n cls.set_active(selection_object)\r\n\r\n @classmethod\r\n def toggle_selection(cls, evento):\r\n cls.on_selection = evento.data['value']\r\n\r\n @classmethod\r\n def update(cls):\r\n events = event.get([KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT])\r\n event.clear()\r\n\r\n # esto es para que se pueda reemplazar un locutor sin tener que reseleccionarlo.\r\n cls.selected.add([i for i in cls.widgets.widgets() if i.is_selected and (i not in cls.selected)])\r\n\r\n for e in events:\r\n mods = key.get_mods()\r\n ctrl = mods & KMOD_CTRL\r\n shift = mods & KMOD_SHIFT\r\n if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):\r\n salir()\r\n\r\n elif e.type == KEYDOWN:\r\n widgets = cls.selected.widgets()\r\n if System.type_mode:\r\n if e.key == K_F3:\r\n System.toggle_typemode('MainTB')\r\n else:\r\n EventHandler.trigger('Key', cls.name, {'key': e.key, 'mod': e.mod})\r\n\r\n elif e.key == K_c:\r\n if len(widgets) == 2 and all([o.numerable for o in widgets]):\r\n widgets.sort(key=lambda o: o.idx) # lower idx's go first\r\n if not shift:\r\n widgets[0].connect(widgets[1])\r\n else:\r\n widgets[0].disconnect(widgets[1])\r\n\r\n elif e.key == K_a and len(widgets) == 2:\r\n base, other = widgets\r\n EventHandler.trigger('AddMidPoint', 'System', {'base': base, 'other': other})\r\n\r\n elif e.key == K_RETURN:\r\n EventHandler.trigger('CreateDialog', cls.name, {'nodes': cls.numerable})\r\n\r\n elif e.key == K_F3:\r\n if any([o.order == 'b' for o in widgets]):\r\n System.toggle_typemode('MainTB')\r\n else:\r\n for widget in widgets:\r\n widget.on_keydown(e)\r\n\r\n elif e.key == K_s:\r\n x, y = mouse.get_pos()\r\n color, text = None, None\r\n if any([o.order == 'a' for o in widgets]):\r\n color = [i for i in widgets if i.order == 'a'][0].color\r\n text = [i for i in widgets if i.order == 'a'][0].text\r\n\r\n if System.area_nodos.collidepoint(x, y) and text is not None:\r\n EventHandler.trigger('AddNode', cls.name, {'text': text, 'pos': [x, y], 'color': color})\r\n\r\n elif e.key == K_d and any([o.order == 'a' for o in widgets]):\r\n widgets.sort(key=lambda o: o.order)\r\n color_namer = widgets.pop(0)\r\n for other in widgets:\r\n other.colorize(color_namer)\r\n\r\n elif len(cls.selected):\r\n for widget in cls.selected.widgets():\r\n widget.on_keydown(e)\r\n\r\n elif e.type == KEYUP:\r\n if len(cls.selected):\r\n for widget in cls.selected.widgets():\r\n widget.on_keyup(e)\r\n\r\n elif e.type == MOUSEBUTTONDOWN: # pos, button\r\n widgets = [w for w in cls.widgets.widgets() if w.selectable and w.rect.collidepoint(e.pos)]\r\n if not len(widgets) and e.button == 1 and cls.active_area.collidepoint(e.pos):\r\n if not shift and not System.type_mode:\r\n cls.selected.empty()\r\n if not ctrl:\r\n EventHandler.trigger('AddSelection', cls.name, {\"pos\": e.pos, 'value': True})\r\n\r\n elif len(widgets) and not len(cls.selected):\r\n cls.selected.sumar([w for w in widgets if w.selectable])\r\n\r\n elif not cls.selected.has(widgets) and e.button == 1 and len(widgets):\r\n order_c = [i for i in widgets if i.order == 'c']\r\n if not ctrl and not System.type_mode and not len(order_c):\r\n cls.selected.empty()\r\n cls.selected.sumar(widgets)\r\n\r\n if len(widgets):\r\n for widget in cls.selected.widgets():\r\n if widget is not cls.selection:\r\n widget.on_mousedown(e)\r\n\r\n elif e.button != 1:\r\n widgets = [w for w in cls.widgets.widgets() if w.numerable]\r\n if ctrl and not shift:\r\n dx, dy = 1, 0\r\n elif shift and not ctrl:\r\n dx, dy = 0, 5\r\n elif ctrl and shift:\r\n dx, dy = 5, 0\r\n else:\r\n dx, dy = 0, 1\r\n\r\n for widget in widgets:\r\n if e.button == 4:\r\n dx *= -1\r\n dy *= -1\r\n elif e.button == 5:\r\n dx *= 1\r\n dy *= 1\r\n\r\n widget.rect.move_ip(dx, dy)\r\n\r\n elif e.type == MOUSEBUTTONUP: # pos, button\r\n if cls.on_selection and e.button == 1:\r\n cls.selection.on_mouseup(e)\r\n selected = [i for i in cls.widgets if cls.selection.rect.contains(i.rect)]\r\n cls.selected.sumar(selected)\r\n\r\n elif e.type == MOUSEMOTION: # pos, rel, buttons\r\n if e.buttons[0] and len(cls.selected) and not shift and not System.type_mode:\r\n for widget in [i for i in cls.selected.widgets() if i.draggable is True]:\r\n widget.on_mousemotion(e)\r\n\r\n elif cls.on_selection and e.buttons[0]:\r\n cls.selection.on_mousemotion(e)\r\n\r\n elif ctrl and e.buttons[0]:\r\n widgets = [w for w in cls.widgets.widgets() if w.selectable and w.draggable]\r\n for widget in widgets:\r\n widget.on_mousemotion(e)\r\n\r\n cls.widgets.update()\r\n\r\n @classmethod\r\n def __repr__(cls):\r\n return cls.name + \" ({} widgets)\".format(str(len(cls.widgets)))\r\n\r\n\r\nEventHandler.register(WidgetHandler.toggle_selection, 'AddSelection', 'EndSelection')\r\n","sub_path":"frontend/globals/widgethandler.py","file_name":"widgethandler.py","file_ext":"py","file_size_in_byte":7725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"12927173","text":"import sys\n \nimport traceback\n \nimport time\n \nfrom math import sqrt\n \n \n \nclass SummaryStatistics(object):\n \n \"\"\"\n \n calculate number of observations, arithmetic mean, median\n \n and sample standard deviation using standard procedures\n \n \"\"\"\n \n def __init__(self):\n \n pass\n \n \n \n def calculate_number_observation(self, one_dimensional_array): \n \n \"\"\"\n \n calculate number of observations\n \n :param one_dimensional_array: numpy one dimensional array\n \n :return number of observations value\n \n \"\"\"\n \n number_observation = 0\n \n try:\n \n number_observation = one_dimensional_array.size \n \n except Exception:\n \n self.print_exception_message()\n \n return number_observation\n \n \n \n def calculate_arithmetic_mean(self, one_dimensional_array, number_observation): \n \n \"\"\"\n \n calculate arithmetic mean\n \n :param one_dimensional_array: numpy one dimensional array\n \n :param number_observation: number of observations\n \n :return arithmetic mean value\n \n \"\"\"\n \n arithmetic_mean = 0.0\n \n try:\n \n sum_result = 0.0\n \n for i in range(number_observation): \n \n sum_result += one_dimensional_array[i] \n \n arithmetic_mean = sum_result / number_observation\n \n except Exception:\n \n self.print_exception_message()\n \n return arithmetic_mean\n \n \n \n def calculate_median(self, one_dimensional_array, number_observation): \n \n \"\"\"\n \n calculate median\n \n :param one_dimensional_array: numpy one dimensional array\n \n :param number_observation: number of observations\n \n :return median value\n \n \"\"\"\n \n median = 0.0\n \n try:\n \n one_dimensional_array.sort() \n \n half_position = number_observation // 2\n \n if not number_observation % 2:\n \n median = (one_dimensional_array[half_position - 1] + one_dimensional_array[half_position]) / 2.0\n \n else:\n \n median = one_dimensional_array[half_position] \n \n except Exception:\n \n self.print_exception_message()\n \n return median\n \n \n \n def calculate_sample_standard_deviation(self, one_dimensional_array, number_observation, arithmetic_mean): \n \n \"\"\"\n \n calculate sample standard deviation\n \n :param one_dimensional_array: numpy one dimensional array\n \n :param number_observation: number of observations\n \n :param arithmetic_mean: arithmetic mean value\n \n :return sample standard deviation value\n \n \"\"\"\n \n sample_standard_deviation = 0.0\n \n try:\n \n sum_result = 0.0\n \n for i in range(number_observation): \n \n sum_result += pow((one_dimensional_array[i] - arithmetic_mean), 2) \n \n sample_variance = sum_result / (number_observation - 1) \n \n sample_standard_deviation = sqrt(sample_variance) \n \n except Exception:\n \n self.print_exception_message()\n \n return sample_standard_deviation\n \n \n \n def print_exception_message(self, message_orientation = \"horizontal\"):\n \n \"\"\"\n \n print full exception message\n \n :param message_orientation: horizontal or vertical\n \n :return none\n \n \"\"\"\n \n try:\n \n exc_type, exc_value, exc_tb = sys.exc_info() \n \n file_name, line_number, procedure_name, line_code = traceback.extract_tb(exc_tb)[-1] \n \n time_stamp = \" [Time Stamp]: \" + str(time.strftime(\"%Y-%m-%d %I:%M:%S %p\"))\n \n file_name = \" [File Name]: \" + str(file_name)\n \n procedure_name = \" [Procedure Name]: \" + str(procedure_name)\n \n error_message = \" [Error Message]: \" + str(exc_value) \n \n error_type = \" [Error Type]: \" + str(exc_type) \n \n line_number = \" [Line Number]: \" + str(line_number) \n \n line_code = \" [Line Code]: \" + str(line_code)\n \n if (message_orientation == \"horizontal\"):\n \n print( \"An error occurred:{};{};{};{};{};{};{}\".format(time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code))\n \n elif (message_orientation == \"vertical\"):\n \n print( \"An error occurred:\\n{}\\n{}\\n{}\\n{}\\n{}\\n{}\\n{}\".format(time_stamp, file_name, procedure_name, error_message, error_type, line_number, line_code))\n \n else:\n \n pass \n \n except Exception:\n \n pass\n\n\n","sub_path":"class_summary_statistics.py","file_name":"class_summary_statistics.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"13121016","text":"\n\nfrom xai.brain.wordbase.nouns._bohemian import _BOHEMIAN\n\n#calss header\nclass _BOHEMIANS(_BOHEMIAN, ):\n\tdef __init__(self,): \n\t\t_BOHEMIAN.__init__(self)\n\t\tself.name = \"BOHEMIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"bohemian\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_bohemians.py","file_name":"_bohemians.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"563081418","text":"from constants import *\nimport random\nimport pygame\n\n\ndef getRandomPipe(Images):\n # y of gap between upper and lower pipe\n gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))\n gapY += int(BASEY * 0.2)\n pipeHeight = Images['pipes'][0].get_height()\n pipeX = SCREENWIDTH + 10\n\n return [\n {'x': pipeX, 'y': gapY - pipeHeight}, # upper pipe\n {'x': pipeX, 'y': gapY + PIPEGAPSIZE}, # lower pipe\n ]\n\ndef checkCrashed(players, upperPipes, lowerPipes,Images,HITMASKS):\n statuses = []\n for idx in range(totalPlayers):\n statuses.append(False)\n\n for idx in range(totalPlayers):\n statuses[idx] = False\n pi = players['index']\n players['w'] = Images['player'][0].get_width()\n players['h'] = Images['player'][0].get_height()\n # if player crashes into ground\n if players['y'][idx] + players['h'] >= BASEY - 1:\n statuses[idx] = True\n playerRect = pygame.Rect(players['x'][idx], players['y'][idx],\n players['w'], players['h'])\n pipeW = Images['pipes'][0].get_width()\n pipeH = Images['pipes'][0].get_height()\n\n for uPipe, lPipe in zip(upperPipes, lowerPipes):\n # upper and lower pipe rects\n uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], pipeW, pipeH)\n lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], pipeW, pipeH)\n\n # player and upper/lower pipe hitmasks\n pHitMask = HITMASKS['player'][pi]\n uHitmask = HITMASKS['pipe'][0]\n lHitmask = HITMASKS['pipe'][1]\n\n # if bird collided with upipe or lpipe\n uCollide = pixelCollision(playerRect, uPipeRect, pHitMask, uHitmask)\n lCollide = pixelCollision(playerRect, lPipeRect, pHitMask, lHitmask)\n\n if uCollide or lCollide:\n statuses[idx] = True\n return statuses\n\ndef pixelCollision(rect1, rect2, hitmask1, hitmask2):\n \"\"\"Checks if two objects collide and not just their rects\"\"\"\n rect = rect1.clip(rect2)\n\n if rect.width == 0 or rect.height == 0:\n return False\n\n x1, y1 = rect.x - rect1.x, rect.y - rect1.y\n x2, y2 = rect.x - rect2.x, rect.y - rect2.y\n\n for x in range(rect.width):\n for y in range(rect.height):\n if hitmask1[x1+x][y1+y] and hitmask2[x2+x][y2+y]:\n return True\n return False\n\ndef getHitmask(image):\n \"\"\"returns a hitmask using an image's alpha.\"\"\"\n mask = []\n for x in range(image.get_width()):\n mask.append([])\n for y in range(image.get_height()):\n mask[x].append(bool(image.get_at((x,y))[3]))\n return mask\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"222646739","text":"import requests\n\n# Telegram bot\n# version 26.02.17\nclass Bot:\n\t# Telegram bot token \n\tTOKEN = ''\n\t# Url to telegram requests\n\tURL = ''\n\toffset = 0\n\n\t# token - telegram bot token\n\tdef __init__(self, token):\n\t\tself.TOKEN = token\n\t\tself.URL = 'https://api.telegram.org/bot' + self.TOKEN\n\t\toffset = 0\n\n\t# Send telegram message\n\tdef send_message(self, data):\n\t\ttry:\n\t\t\tresponse = requests.post(self.URL + '/sendMessage', params=data)\n\t\texcept:\n\t\t\tprint('Send message error')\n\t\treturn response.status_code\n\n\t# Return answer by incoming message\n\tdef create_answer(self, update):\n\t\tmessage = ''\n\t\ttry:\n\t\t\tmessage = update['message']['text']\n\t\texcept:\n\t\t\treturn \"Please, send me text.\"\n\t\tmessage = message.lower() # Convert to lower case\n\n\t\tif message == '/start':\n\t\t\tmsg = \"Здравствуйте! Это бот для продаже жидкости для vape. \"\n\t\t\tmsg += \"Если вы живете в Смоленске, то вам невероятно повезло! \"\n\t\t\tmsg += \"У вас есть шанс приобрести жидкость всего за 150р за 30мл! \"\n\t\t\tmsg += \"Для этого вам нужно отправить команду /buy и вкус жидкости. \"\n\t\t\tmsg += \"Например «/buy яблочный пирог» или «/buy bubble gum». \"\n\t\t\tmsg += \"Для того что бы узнать доступные вкусы введите команду /tastes. \"\n\t\t\tmsg += \"Удачных покупок!\"\n\t\t\treturn msg\n\t\telif message == '/tastes':\n\t\t\tmsg = \"Список доступных вкусов жидкости для парения:\\n\"\n\t\t\tmsg += \"• Bubble gum.\\n\"\n\t\t\tmsg += \"• Яблочный пирог.\"\n\t\t\treturn msg\n\t\telif message == '/prices':\n\t\t\treturn \"Цены на жидкость для vape: \\n30мл - 150₽\"\n\t\telif message == 'creator':\n\t\t\treturn \"Bot created by Fomchenkov Vyacheslav\"\n\t\telif message == 'hello':\n\t\t\tuser_name = update['message']['from']['first_name']\n\t\t\tuser_surname = update['message']['from']['last_name']\n\t\t\treturn \"Hello, \" + user_name + \" \" + user_surname + \"!\"\n\t\telif message.startswith('/buy'):\n\t\t\tresponse = message.split(\" \")\n\t\t\tif len(response) <= 1:\n\t\t\t\tmsg = \"Некорректная команда. \"\n\t\t\t\tmsg += \"Формат команды «/buy вкус жидкости». \"\n\t\t\t\tmsg += \"Попробуйте еще раз.\"\n\t\t\t\treturn msg\n\t\t\tresponse = response[1:]\n\t\t\tzakaz = ''\n\t\t\tfor x in response:\n\t\t\t\tzakaz += x + ' '\n\t\t\tzakaz = zakaz.strip()\n\n\t\t\t# Send me notification about custom\n\t\t\tanswer = \"Пользователь @\" + update['message']['from']['username'] \n\t\t\tanswer += \" хочет заказать у вас \"\n\t\t\tanswer += \"жидкость для vape со вкусом «\" + str(zakaz) + \"»\"\n\t\t\tanswer += \". Свяжитесь с ним для подтверждения заказа.\"\n\t\t\tmy_chat_id_with_bot = 217166737\n\t\t\tdata = {\n\t\t\t\t'chat_id': my_chat_id_with_bot,\n\t\t\t\t'text': answer,\n\t\t\t\t'parse_mode': 'HTML'\n\t\t\t}\n\t\t\tself.send_message(data)\n\n\t\t\tmsg = \"Ваш заказ успешно принят. Вы заказали \"\n\t\t\tmsg += \"жидкость со вкусом «\" + str(zakaz) + \"». В ближайшее время \"\n\t\t\tmsg += \"мой хозяин свяжится с вами и подтвердит ваш заказ. Всего хорошего!\"\n\t\t\treturn msg\n\t\telse:\n\t\t\tmsg = 'Некорректное сообщение. '\n\t\t\tmsg += 'Пожалуйста, попробуйте ввести команду снова☺'\n\t\t\treturn msg\n\n\t# Update telegram stats\n\tdef get_updates(self):\n\t\tdata = {'offset': self.offset}\n\n\t\ttry:\n\t\t\tresponse = requests.get(self.URL + '/getUpdates', params=data)\n\t\texcept:\n\t\t\tprint('Error getting updates')\n\t\t\treturn False\n\n\t\tif not response.status_code == 200: return False\n\t\tif not response.json()['ok']: return False\n\n\t\tprint(response.json())\n\t\tresult = response.json()['result']\n\n\t\tfor update in result:\n\t\t\tself.offset = int(update['update_id'])\n\t\t\tself.offset += 1\n\t\t\tanswer = self.create_answer(update)\n\n\t\t\tdata = {\n\t\t\t\t'chat_id': update['message']['chat']['id'],\n\t\t\t\t'text': answer,\n\t\t\t\t# 'reply_to_message_id': update['message']['message_id'],\n\t\t\t\t'parse_mode': 'HTML'\n\t\t\t}\n\t\t\tself.send_message(data)\n\n\t# Loop to requests to server\n\tdef polling(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tself.get_updates()\n\t\t\texcept KeyboardInterrupt as e:\n\t\t\t\tprint(\"[Bot stoped]\")\n\ndef main():\n\tTOKEN = '325205266:AAEQ2KMas9-KhCf4VZlv_qkdAgJbVW991Pk'\n\tbot = Bot(TOKEN)\n\tbot.polling()\t\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"113744564","text":"import sys\n\nfilm_id = int(sys.argv[1])\n\nimdb = {\n 111161: [{\"rating\": 8}, {\"rating\": 9},\n {\"rating\": 10}, {\"rating\": 9}, {\"rating\": 10}],\n 68646: [{\"rating\": 8}, {\"rating\": 10},\n {\"rating\": 9}, {\"rating\": 9}, {\"rating\": 9}],\n 468569: [{\"rating\": 10}, {\"rating\": 10},\n {\"rating\": 8}, {\"rating\": 8}],\n 71562: [{\"rating\": 9}, {\"rating\": 9}, {\"rating\": 10}],\n 167260: [{\"rating\": 8}, {\"rating\": 7},\n {\"rating\": 9}, {\"rating\": 9}, {\"rating\": 8}, {\"rating\": 9}]\n}\n\nprint(imdb[film_id][-1][\"rating\"])\n\n\"\"\"\nПОСЛЕДНИЙ РЕЙТИНГ\nНиже находится словарь imdb с рейтингом фильмов по версии IMDB. \nКлюч словаря отвечает за идентификатор фильма, \nа значение содержит список словарей, \nкаждый из которых состоит из одного элемента с ключом rating.\n\nНапишите программу, \nкоторая получает из аргументов командной строки идентификатор фильма, \nа затем выводит последнее значение рейтинга, \nкоторый ему поставили пользователи.\n\nПример использования:\n> python program.py 68646\n> 9\n\"\"\"","sub_path":"shultais_courses/dictionaries/intro_to_dictionaries/last_raiting.py","file_name":"last_raiting.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"421714911","text":"import sys\nsys.stdin = open(\"input.txt\", \"rt\")\n\ntimestamp = [1,2,2,3,4,5,6,6,13,16]\ntimestamp_count = len(timestamp)\ntop = [10,15]\n\ndef requestsServed(timestamp, top):\n # Write your code here\n servedRequestIdx = []\n for t in top:\n cntServed = 0\n filteredTimestamp = [s for i, s in enumerate(timestamp) if i not in servedRequestIdx]\n\n for i, request in enumerate(filteredTimestamp[::-1]):\n if cntServed >= 5:\n break\n elif request <= t:\n cntServed += 1\n servedRequestIdx.append(len(filteredTimestamp)-i-1)\n \n return len(servedRequestIdx)\n\nprint(requestsServed(timestamp, top))\n\n\"\"\"\nspace = [2,5]\nspace_count = len(space)\nx = 2\n\ndef segment(x, space):\n max = -1\n for i in range(space_count-x+1):\n minima = min(space[i:i+x])\n if max < minima:\n max = minima\n return max\n\nprint(segment(x,space))\n\"\"\"\n\n\"\"\"\nN, M = map(int, input().split())\narr = list(map(int, input().split()))\n\ndef countDVD(capacity):\n sum = 0\n cnt = 1\n for music in arr:\n if sum + music > capacity:\n cnt += 1\n sum = music\n else:\n sum += music\n return cnt\n\nN, M = map(int, input().split())\narr = list(map(int, input().split()))\n\nlow = 1\nhigh = sum(arr)\nminCapacity = -1\nwhile low <= high:\n mid = (low + high) // 2\n if countDVD(mid) <= M:\n high = mid - 1\n minCapacity = mid\n elif countDVD(mid) > M:\n low = mid + 1\n\nprint(minCapacity)\n\"\"\"\n","sub_path":"section3/3_DVD/dvd.py","file_name":"dvd.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"421153507","text":"\"\"\"Definition of the Vector Magnitude Component.\"\"\"\n\n\nfrom six import string_types\n\nimport numpy as np\n\nfrom openmdao.core.explicitcomponent import ExplicitComponent\n\n\nclass VectorUnitizeComp(ExplicitComponent):\n \"\"\"\n Computes the unitized vector\n\n math::\n \\hat{a} = \\bar{a} / np.sqrt(np.dot(a, a))\n\n where a is of shape (vec_size, n)\n\n \"\"\"\n\n def initialize(self):\n \"\"\"\n Declare options.\n \"\"\"\n self.options.declare('vec_size', types=int, default=1,\n desc='The number of points at which the vector magnitude is computed')\n self.options.declare('length', types=int, default=3,\n desc='The length of the input vector at each point')\n self.options.declare('in_name', types=string_types, default='a',\n desc='The variable name for input vector.')\n self.options.declare('units', types=string_types, default=None, allow_none=True,\n desc='The units for the input and output vector.')\n self.options.declare('out_name', types=string_types, default='a_mag',\n desc='The variable name for output unitized vector.')\n\n def setup(self):\n \"\"\"\n Declare inputs, outputs, and derivatives for the vector magnitude component.\n \"\"\"\n opts = self.options\n vec_size = opts['vec_size']\n m = opts['length']\n\n self.add_input(name=opts['in_name'],\n shape=(vec_size, m),\n units=opts['units'])\n\n self.add_output(name=opts['out_name'],\n val=np.zeros(shape=(vec_size, m)),\n units=opts['units'])\n\n row_idxs = np.repeat(np.arange(vec_size * m, dtype=int), m)\n temp = np.reshape(np.arange(vec_size * m, dtype=int), newshape=(vec_size, m))\n col_idxs = np.repeat(temp, m, axis=0).ravel()\n self.declare_partials(of=opts['out_name'], wrt=opts['in_name'],\n rows=row_idxs, cols=col_idxs, val=1.0)\n\n def compute(self, inputs, outputs):\n \"\"\"\n Compute the vector magnitude of input.\n\n Parameters\n ----------\n inputs : Vector\n unscaled, dimensional input variables read via inputs[key]\n outputs : Vector\n unscaled, dimensional output variables read via outputs[key]\n \"\"\"\n opts = self.options\n a = inputs[opts['in_name']]\n a_mag = np.sqrt(np.einsum('ni,ni->n', a, a))\n outputs[opts['out_name']] = a / a_mag[:, np.newaxis]\n\n def compute_partials(self, inputs, partials):\n \"\"\"\n Compute the sparse partials for the vector magnitude w.r.t. the inputs.\n\n Parameters\n ----------\n inputs : Vector\n unscaled, dimensional input variables read via inputs[key]\n partials : Jacobian\n sub-jac components written to partials[output_name, input_name]\n \"\"\"\n opts = self.options\n m = opts['length']\n a = inputs[opts['in_name']]\n a_mag = np.sqrt(np.einsum('ni,ni->n', a, a))\n f = a[0, :]\n g = a_mag\n gp = a.ravel() / np.sqrt(np.einsum('ni,ni->n', a, a))\n g_squared = np.einsum('ni,ni->n', a, a)\n\n print(a_mag - (a * a[0] / a_mag)[0] / (a_mag ** 2))\n\n # print()\n # print(f)\n # # print(fp)\n # print(g)\n # print(gp)\n # print()\n\n partials[opts['out_name'], opts['in_name']] = 88\n\n print()\n print('gp')\n print(gp.shape)\n print('f')\n print(f.shape)\n\n print((g - gp[0] * f[0]) / g_squared, end='')\n print((g - gp[1] * f[0]) / g_squared, end='')\n print((g - gp[2] * f[0]) / g_squared)\n\n print((g - gp[0] * f[1]) / g_squared, end='')\n print((g - gp[1] * f[1]) / g_squared, end='')\n print((g - gp[2] * f[1]) / g_squared)\n\n print((g - gp[0] * f[2]) / g_squared, end='')\n print((g - gp[1] * f[2]) / g_squared, end='')\n print((g - gp[2] * f[2]) / g_squared)\n\n diag = (g - gp * f) * g_squared\n\n\n\n #\n # \"f' * g - g' * f / 2g\"\n # fp = 1\n # g = np.sqrt(np.einsum('ni,ni->n', a, a))[:, np.newaxis]\n # gp = a.ravel() / np.repeat(np.sqrt(np.einsum('ni,ni->n', a, a)), opts['length'])\n # f = a\n #\n # # Use the following for sparse partials\n # partials[opts['out_name'], opts['in_name']] = a.ravel() / np.repeat(np.sqrt(np.einsum('ni,ni->n', a, a)), opts['length'])\n","sub_path":"CADRE/attitude_dymos/VectorUnitizeComp.py","file_name":"VectorUnitizeComp.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"96343613","text":"import torch\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nfrom collections import OrderedDict\n\n# pytorch: y = x A.T +b\nclass FullyConnectedNetwork(object):\n \n # activation functions\n sigmoid = nn.Sigmoid()\n tanh = nn.Tanh()\n relu = nn.ReLU()\n soft_max = nn.Softmax(dim=1) # Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns\n log_soft_max = nn.LogSoftmax(dim=1)\n \n # loss functions\n cross_entropy_loss = nn.CrossEntropyLoss() \n nl_loss = nn.NLLLoss()\n \n # Optimizer classes\n Adam = optim.Adam\n Sgd = optim.SGD\n \n def __init__(self, loss_function, optimizer, model=None, input_size=None, layer_sizes=None, activation_functions=None): \n assert (isinstance(model, nn.Module) or \n all(arg is not None for arg in [input_size, layer_sizes, activation_functions])), \\\n 'Invalid network initialization'\n \n self._criterion = loss_function\n self._Optimizer = optimizer\n self._model = None \n \n if isinstance(model, nn.Module): \n self._model = model\n else:\n assert len(layer_sizes) == len(activation_functions), 'layer_sizes/activation_functions mismatch'\n units = [input_size] + layer_sizes\n activations = [None] + activation_functions\n layers = OrderedDict()\n for l in range(1, len(units)):\n layers['fc%d'% l] = nn.Linear(units[l-1], units[l])\n layers['ac%d'% l] = activations[l]\n self._model = nn.Sequential(layers) \n \n @property\n def model(self):\n return self._model\n \n def __repr__(self): \n rp = f'FullyConnectedNetwork(\\nOptimizer:{self._Optimizer.__name__}\\nCriterion:{repr(self._criterion)[:-3]}\\nLayers:'\n rp += repr(self._model).replace('Sequential(', '')\n return rp \n \n def train(self, trainset, testset, lr, epochs, batch_size=64): \n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=True)\n optimizer = self._Optimizer(self._model.parameters(), lr=lr)\n \n for e in range(epochs):\n running_loss = 0\n for samples, labels in trainloader:\n samples = samples.view(samples.shape[0], -1) \n \n logits = self._model(samples)\n loss = self._criterion(logits, labels)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n running_loss += loss.data\n else:\n # inference\n test_accuracy = 0\n test_loss = 0\n with torch.no_grad():\n for samples, labels in testloader:\n samples = samples.view(samples.shape[0], -1)\n logits = self._model(samples)\n \n test_loss += self._criterion(logits, labels)\n top_logit, top_class = logits.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n test_accuracy += torch.mean(equals.type(torch.FloatTensor)) \n \n print(f'Epoch {e}.', \n f'Training loss: {running_loss/len(trainloader) :.3f},',\n f'Test loss: {test_loss/len(testloader) :.3f},',\n f'Test Accuracy: {test_accuracy.item()/len(testloader)*100 :.2f}%')","sub_path":"deeplearning/torchnets.py","file_name":"torchnets.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"234855478","text":"import os.path as path\nfrom iggyref.utils.util import md5Checksum, sumChecksum\n\nclass rFile(object):\n def __init__(self, name, fprop = None):\n self.name = name\n self.ftpSubDir = ''\n self.checksumFile = ''\n self.checksumType = ''\n if fprop:\n if 'ftpSubDir' in fprop.keys():\n self.ftpSubDir = fprop['ftpSubDir']\n if 'checksumFile' in fprop.keys():\n self.checksumFile = fprop['checksumFile']\n if 'checksumType' in fprop.keys():\n self.checksumType = fprop['checksumType']\n self.ftpPath = None\n self.remoteTimeString = None\n self.localPath = None\n self.localChecksum = None\n self.remoteChecksum = ''\n self.prevChecksum = ''\n\n def setLocalChecksum(self):\n if self.checksumType in ['', 'md5', 'md5sum']:\n self.localChecksum = md5Checksum(self.localPath)\n elif self.checksumType == 'sum':\n self.localChecksum = sumChecksum(self.localPath)\n else:\n raise Exception('Unrecognized checksum type: %s (filename: %s)' % (self.checksumType, self.name))\n\n def __repr__(self):\n return '' % self.name\n\n","sub_path":"iggyref/rFileClass.py","file_name":"rFileClass.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"538704311","text":"from util import Timer\nimport numpy as np\n\nN = 10000000\n\ndef bench_getitem():\n myarray = np.zeros(10)\n with Timer('getitem'):\n total = 0\n for i in xrange(N/10):\n myarray[5]\n\ndef bench_mean():\n myarray = np.array([12.34])\n with Timer('np.mean'):\n for i in xrange(N/100):\n np.mean(myarray)\n\nbench_getitem()\nbench_mean()\n","sub_path":"bench_np.py","file_name":"bench_np.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394973935","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('django_comments', '0002_update_user_email_field_length'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Application',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=50, verbose_name='Name of the show')),\n ('topic', models.CharField(max_length=200, verbose_name='List of common topics')),\n ('description', models.TextField(default=b'', verbose_name='Longer description of the show', blank=True)),\n ('homepage', models.URLField(default=b'', verbose_name='Homepage of the Show', blank=True)),\n ('link_to_episode', models.URLField(default=b'', verbose_name='Link to an episode', blank=True)),\n ('schedule', models.CharField(max_length=200, verbose_name='How often do are new episodes published')),\n ('contact_email', models.EmailField(max_length=254, verbose_name='Contact email')),\n ('contact_name', models.CharField(max_length=255, verbose_name='Full name')),\n ('incoming_time', models.DateTimeField(auto_now_add=True, verbose_name='Date of application')),\n ('status', models.CharField(default=b'1_OPEN', max_length=20, verbose_name='Status', choices=[(b'1_OPEN', 'Open'), (b'2_ACCEPTED', 'Accepted'), (b'3_DENIED', 'Denied')])),\n ('rt_id', models.IntegerField(null=True, verbose_name='ID for this application in RT, if known', blank=True)),\n ],\n options={\n 'ordering': ['status', 'incoming_time'],\n },\n ),\n migrations.CreateModel(\n name='ApplicationToken',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('token', models.CharField(unique=True, max_length=12)),\n ('incoming_time', models.DateTimeField(auto_now_add=True, verbose_name='Date of application')),\n ('show_name', models.CharField(max_length=50)),\n ('rt_id', models.IntegerField(null=True, verbose_name='ID for this application in RT, if known', blank=True)),\n ('application', models.ForeignKey(blank=True, to='radioportal_review.Application', null=True)),\n ('creator', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['application', 'incoming_time'],\n },\n ),\n migrations.CreateModel(\n name='Review',\n fields=[\n ('comment_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_comments.Comment')),\n ('vote', models.CharField(default=b'NO', max_length=11, verbose_name='Vote', choices=[(b'YES', 'Yes'), (b'NO', 'No'), (b'MAYBE', 'Maybe, specify in text'), (b'INFOMISSING', 'Addional informations required')])),\n ('depth', models.CharField(default=b'NONE', max_length=8, verbose_name='Review Depth', choices=[(b'NONE', 'I did not looked at anything'), (b'KNOWN', 'I know this already'), (b'HOMEPAGE', 'I looked at the homepage'), (b'EPISODE', 'I listened to one episode (mention in text)'), (b'EPISODES', 'I listened to some episodes')])),\n ('audio', models.CharField(default=b'-1', max_length=10, verbose_name='Audio Quality', choices=[(b'-1', \"Don't know\"), (b'1', '1 (Very Bad)'), (b'2', '2'), (b'3', '3'), (b'4', '4'), (b'5', '5 (Very Good)')])),\n ],\n options={\n 'abstract': False,\n },\n bases=('django_comments.comment',),\n ),\n ]\n","sub_path":"radioportal_review/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"563921533","text":"from concurrent.futures import ThreadPoolExecutor\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\n\nclass ConcurrentListCrawler(object):\n\n def __init__(self,url_list, threads): \n self.urls = url_list \n self.results={}\n self.max_threads = threads\n print(\"Number of threads \"+str(self.max_threads))\n\n def __make_request(self, url): \n try:\n r=requests.get(url=url, timeout=20)\n r.raise_for_status() \n except requests.exceptions. Timeout:\n r = requests.get(url=url, timeout=60) \n except requests.exceptions.ConnectionError:\n\n r = requests.get(url-query, timeout=60)\n\n except requests.exceptions.RequestException as e:\n raise e\n\n return r.url, r.text\n\n def __parse_results(self, url, html): \n try:\n soup = BeautifulSoup(html, 'html.parser') \n title = soup.find('title').get_text() \n except Exception as e:\n\n raise e\n\n if title: \n self.results[url]=title\n\n def wrapper(self, url):\n\n url, html=self.__make_request(url)\n self.__parse_results(url, html)\n\n def run_script(self):\n with ThreadPoolExecutor(max_workers=min(len(self.urls),self.max_threads)) as Executor:\n jobs=[Executor.submit(self.wrapper, u) for u in self.urls]\n\nif __name__ =='__main__':\n q=time.time ()\n example = ConcurrentListCrawler([\"https://timesofindia.indiatimes.com/defaultinterstitial.cms\",\n\"https://www.theguardian.com/international\",\n\"https://www.apple.com/in/?afid=p238%7CsdUuvv563-dc_mtid_187079nc38483_pcrid_474706300243_pgrid_109516736379_&cid=aos-IN-kwgo-brand--slid---product-\",\n\"https://www.samsung.com/in/\",\n\"https://www.amazon.jobs/en-gb/\",\n\"https://www.fidelity.com/\",\n\"https://www.fidelity.com/news/overview\",\n\"https://www.amazon.jobs/en-gb/faqs\",\n\"https://www.maybelline.com/\",\n\"https://www.nykaa.com/skin/c/8377?root=nav_1&dir=desc&order=popularity\",\n\"https://www.nykaa.com/best-wellness-products-online-sale?root=nav_1&dir=desc&order=popularity\",\n\"https://www.myntra.com/shop/women\",\n\"https://vit.ac.in/\",\n\"https://vtop.vit.ac.in/vtop/initialProcess\",\n\"https://practice.geeksforgeeks.org/problems/count-the-zeros2550/1/?company[]=Amazon&difficulty[]=0&page=1&query=company[]Amazondifficulty[]0page1\",\n\"https://en.wikipedia.org/wiki/Taylor_Swift\",\n\"https://en.wikipedia.org/wiki/Billboard_200\",\n\"https://en.wikipedia.org/wiki/Calliotropis_solomonensis\",\n\"https://en.wikipedia.org/wiki/Antonio_Morelli\",\n\"https://en.wikipedia.org/wiki/Harry_Styles\",\n\"https://en.wikipedia.org/wiki/One_Direction\",\n\"https://en.wikipedia.org/wiki/Louis_Tomlinson\",\n\"https://en.wikipedia.org/wiki/Liam_Payne\",\n\"https://en.wikipedia.org/wiki/Niall_Horan\",\n\"https://en.wikipedia.org/wiki/Zayn_Malik\"],25)\n example.run_script()\n q1=time.time()\n\n#print(example, results)\n for key, val in example.results.items (): \n print (key+\": \"+val)\n print(\"Time taken to crawl the given web pages: \"+str(q1-q))\n","sub_path":"concurrent25.py","file_name":"concurrent25.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"85726732","text":"\n\n#calss header\nclass _SLED():\n\tdef __init__(self,): \n\t\tself.name = \"SLED\"\n\t\tself.definitions = [u'an object used for travelling over snow and ice with long, narrow strips of wood or metal under it instead of wheels. It can be either a low frame, or a vehicle like a carriage pulled by horses or dogs.']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_sled.py","file_name":"_sled.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"633405688","text":"#!/usr/bin/env python3\n\nimport unittest\nfrom unittest.mock import patch, Mock\n\nimport sap.cli.helpers\n\nfrom mock import (\n ConsoleOutputTestCase\n)\n\nclass TestConsoleHeartBeat(ConsoleOutputTestCase, unittest.TestCase):\n\n def getBeater(self, period):\n return sap.cli.helpers.ConsoleHeartBeat(self.console, period)\n\n def test_heart_beat_not_start(self):\n beater = self.getBeater(0)\n beater._run()\n\n self.assertConsoleContents(console=self.console)\n\n @patch('sap.cli.helpers.time.sleep')\n def test_heart_beat_line_break(self, fake_sleep):\n beater = self.getBeater(5)\n\n self.remaining_beats = 199\n def stop_at_zero(timeout):\n self.remaining_beats -= 1\n\n if self.remaining_beats == 0:\n beater._stop()\n\n fake_sleep.side_effect = stop_at_zero\n\n beater._run()\n\n self.maxDiff = None\n self.assertConsoleContents(console=self.console, stdout=\n'''.........50s.........100s.........150s.........200s.........250s.........300s.........350s.........400s\n.........450s.........500s.........550s.........600s.........650s.........700s.........750s.........800s\n.........850s.........900s.........950s.........\n''')\n\n @patch('sap.cli.helpers.time.sleep')\n def test_heart_beat_line_break_no_empty_line(self, fake_sleep):\n beater = self.getBeater(5)\n\n self.remaining_beats = 80\n def stop_at_zero(timeout):\n self.remaining_beats -= 1\n\n if self.remaining_beats == 0:\n beater._stop()\n\n fake_sleep.side_effect = stop_at_zero\n\n beater._run()\n\n self.maxDiff = None\n self.assertConsoleContents(console=self.console, stdout=\n'''.........50s.........100s.........150s.........200s.........250s.........300s.........350s.........400s\n''')\n\n @patch('sap.cli.helpers.time.sleep')\n def test_heart_beat_line_break_with_elapsed(self, fake_sleep):\n beater = self.getBeater(5)\n\n self.remaining_beats = 85\n def stop_at_zero(timeout):\n self.remaining_beats -= 1\n\n if self.remaining_beats == 0:\n beater._stop()\n\n fake_sleep.side_effect = stop_at_zero\n\n beater._run()\n\n self.maxDiff = None\n self.assertConsoleContents(console=self.console, stdout=\n'''.........50s.........100s.........150s.........200s.........250s.........300s.........350s.........400s\n.....\n''')\n\n @patch('sap.cli.helpers.time.sleep')\n def test_heart_beat_line_break(self, fake_sleep):\n fake_sleep.side_effect = Exception()\n beater = self.getBeater(1)\n # HACK!!!\n beater._state = sap.cli.helpers.TaskStates.RUNNING\n\n beater._run()\n self.assertEqual(beater._state, sap.cli.helpers.TaskStates.RUNNING)\n\n\n @patch('sap.cli.helpers.threading.Thread')\n def test_heart_beat_context_start_thread(self, fake_thread):\n fake_instance = Mock()\n fake_thread.return_value = fake_instance\n\n with sap.cli.helpers.ConsoleHeartBeat(self.console, 3) as beater:\n self.assertIsNotNone(beater._thread)\n self.assertEqual(beater._sleep_period_s, 3)\n self.assertEqual(beater._console, self.console)\n fake_thread.assert_called_once_with(target=beater._run)\n beater._state = sap.cli.helpers.TaskStates.RUNNING\n\n fake_instance.start.assert_called_once_with()\n fake_instance.join.assert_called_once_with()\n self.assertIsNone(beater._thread)\n self.assertEqual(beater._state, sap.cli.helpers.TaskStates.TERMINATING)\n\n","sub_path":"test/unit/test_sap_cli_helpers.py","file_name":"test_sap_cli_helpers.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"18165306","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\n\n# Create your views here.\n\nfrom doctorkot.models import Doctor\nimport random\n\ndef unofficial(request):\n\treply = ''\n\t\n\tif request.method == \"POST\":\n\t\tgreet = random.choice([\"Привет, \", \"Добро пожаловать к доктору Коту, \", \"Добрый день, \", \"Приветствую, \"]).decode('utf-8')\n\t\tname = request.POST['thename']\n\t\twords = random.choice([\". Как я понимаю, у вас \", \". Очевидно, у вас \", \". Очевидно, у тебя \", \". Все понятно, у вас \"]).decode('utf-8')\n\t\tdesc = request.POST['thediag']\n\t\tsovet = random.choice([\"Это норма.\", \"В данном случае поможет отвар ромашки.\", \"Не ссы все пройдет.\", \"В таких случаях я предлагаю операцию.\", \"К сожалению, это смертельно.\", \"Вам нужно сдать анализы крови и сделать снимки.\", \"У моей бабушки так было за три дня до смерти.\", \"Ваш случай довольно сложный, мне нужно посоветоваться с доктором псом.\"]).decode('utf-8')\n\t\treply = greet + name + words + desc + '. ' + sovet\n\n\n\n\tcontext = {\n\t'reply': reply\n\t}\n\treturn render(request, 'doctorkot/doctor.html', context)\n\ndef official(request):\n\tprices = Prices.objects.all().order_by(\"pub_date\")\n\t\n\tcontext = {\n\t'prices':prices,\n\t}\n\treturn render(request, 'doctorkot/doctor1.html', context)","sub_path":"doctorkot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"38110455","text":"from keras.datasets import cifar10\r\nfrom keras.utils import np_utils\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import Dropout\r\nfrom keras.layers import Flatten\r\nfrom keras.layers import GlobalAveragePooling2D\r\nfrom keras.optimizers import SGD\r\nfrom keras.layers.convolutional import Conv2D\r\nfrom keras.layers.convolutional import MaxPooling2D\r\n\r\n(train_x, train_y),(test_x, test_y)=cifar10.load_data()\r\n \r\ntrain_x=train_x.astype('float32')\r\ntest_x=test_x.astype('float32')\r\n \r\ntrain_x=train_x/255.0\r\ntest_x=test_x/255.0\r\n\r\ntrain_y=np_utils.to_categorical(train_y)\r\ntest_y=np_utils.to_categorical(test_y)\r\n \r\nnum_classes=test_y.shape[1]\r\n\r\nmodel=Sequential()\r\nmodel.add(Conv2D(32,(3,3),input_shape=(32,32,3),\r\n activation='relu'))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(MaxPooling2D(pool_size=(2,2)))\r\nmodel.add(Conv2D(64,(3,3),activation='relu'))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(MaxPooling2D(pool_size=(2,2)))\r\nmodel.add(Conv2D(128,(3,3),activation='relu'))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(MaxPooling2D(pool_size=(2,2)))\r\n# model.add(Flatten())\r\nmodel.add(GlobalAveragePooling2D())\r\nmodel.add(Dense(128,activation='relu'))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Dense(512,activation='relu'))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Dense(num_classes, activation='softmax'))\r\n\r\nsgd=SGD(lr=0.01,momentum=0.9,decay=(0.01/25),nesterov=False)\r\n \r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer=sgd,\r\n metrics=['accuracy'])\r\n\r\nmodel.fit(train_x,train_y,\r\n validation_data=(test_x,test_y),\r\n epochs=20,batch_size=32)\r\n\r\n_,acc=model.evaluate(test_x,test_y)\r\nprint(acc*100)\r\n\r\n# model.save(\"model1_cifar_10epoch.h5\")","sub_path":"Image Classification on CIFAR-10/Cifar-10.py","file_name":"Cifar-10.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"386388708","text":"\"\"\"\nFunctions for dealing with samples:\n - make_sample: simply create a dataframe representing a sample\n - split: split a sample using a column value\n - convert_to_decimal: convert lat-lon coordinates from a deg, min, sec format to a decimal one\n - ratios_and_isotopes: print available isotopes on chronokit\n\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom .radiogenic.RadioConstants import u_th_pb_df\nfrom .cosmogenic.CosmoConstants import he3_df\n\n\ndef make_sample(datafile, sheet_name=0, usecols=None, names=None):\n \"\"\"\n Creates a dataframe representing a sample, using a csv or excel file as input\n\n Args:\n datafile - path to sample file, string\n\n Returns:\n sample - sample dataframe, dataframe\n \"\"\"\n try:\n sample = pd.read_csv(datafile, usecols=usecols, names=names)\n except UnicodeDecodeError:\n sample = pd.read_excel(\n datafile, sheet_name=sheet_name, usecols=usecols)\n\n return sample\n\n\ndef split(sample, column, new_index=False):\n \"\"\"\n Split sample using pandas.groupby\n\n Args:\n sample - sample dataframe\n column - column to split, str\n\n Returns:\n sample_list - sample dataframes, list\n \"\"\"\n unique_names = sample[column].unique()\n groups = sample.groupby(column)\n sample_list = [groups.get_group(i) for i in unique_names]\n\n if new_index:\n for i in sample_list:\n i.set_index(np.arange(0, len(i), 1), inplace=True)\n\n return sample_list\n\n\ndef convert_to_decimal(sample, coordinates, inplace=False):\n \"\"\"\n Function to convert coordinates from XXº XX' XX'' to XX.XXXX, adapted from:\n https://stackoverflow.com/questions/10852955/python-batch-convert-gps-positions-to-lat-lon-decimals\n\n Args:\n coordinates: numerical value of a coordinate in deg, min, sec N/S (e.g: lat or lon)\n\n Returns:\n decimal_coord: converted decimal value of a coordinate\n \"\"\"\n coord_values = sample[coordinates].unique()\n coord_list = []\n\n for i in coord_values:\n old = str(i)\n direction = {'N': 1, 'S': -1, 'E': 1, 'W': -1}\n new = old.replace(\"°\", \" \").replace(\n \"'\", \" \").replace(\"\\\"\", \" \").replace(\"º\", \" \")\n new = new.split()\n new_dir = new.pop()\n den = [1.0, 60.0, 3600.0]\n\n decimal_coord = sum(\n [float(i)/d for i, d in zip(new, den)])*direction[new_dir]\n\n coord_list.append(decimal_coord)\n\n sample[coordinates].replace(i, decimal_coord, inplace=inplace)\n\n return coord_list\n\n\ndef ratios_and_isotopes():\n \"\"\"\n Returns a dataframe with available isotopes and ratios from the module.\n\n Index - Available nuclides and ratios\n Attributes - Halflifes, Decay Constants\n \"\"\"\n\n he3 = he3_df()\n u_th_pb = u_th_pb_df()\n\n # Add cosmogenic and radiogenic flags\n he3['Genesis'] = 'cosmogenic'\n u_th_pb['Genesis'] = 'radiogenic'\n\n # Concatening dataframes\n df_list = [he3, u_th_pb]\n ri_df = pd.concat(df_list)\n\n return ri_df\n","sub_path":"chronokit/SampleTools.py","file_name":"SampleTools.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"510296632","text":"# -*- coding:utf-8 -*-\n\nfrom api.api import API\nfrom pages.android.common.super_page import SuperPage\nfrom pages.android.ffan.child_category_page_configs import ChildCategoryPageConfigs as CCPC\n\n\nclass ChildCategoryPage(SuperPage):\n '''\n 作者 刘涛\n 首页=>亲子\n '''\n def __init__(self, testcase, driver, logger):\n super(ChildCategoryPage, self).__init__(testcase , driver, logger)\n\n def validSelf(self):\n '''\n usage : 进入美食页面,根据餐饮的textview,检查找餐饮页面是否加载出来.\n '''\n API().assertElementByResourceId(self.testcase,\n self.driver,\n self.logger,\n CCPC.resource_id_ll_child_play_ll,\n CCPC.click_on_button_timeout)\n\n def clickListFirstItem(self):\n '''\n usage : 点击门店的listView\n '''\n tempText = API().getTextByXpath(self.testcase,\n self.driver,\n self.logger,\n CCPC.xpath_store_list_1,\n CCPC.click_on_button_timeout)\n\n API().clickElementByXpath(self.testcase,\n self.driver,\n self.logger, \n CCPC.xpath_store_list_1,\n CCPC.click_on_button_timeout)\n\n return tempText\n\n def clickOnChildPlay(self):\n '''\n usage : 点击亲子游乐\n '''\n API().clickElementByResourceId(self.testcase,\n self.driver,\n self.logger,\n CCPC.resource_id_ll_child_play_ll,\n CCPC.click_on_button_timeout)\n\n def clickOnChildEducation(self):\n '''\n usage : 点击儿童教育\n '''\n API().clickElementByResourceId(self.testcase,\n self.driver,\n self.logger,\n CCPC.resource_id_ll_child_education_ll,\n CCPC.click_on_button_timeout)\n\n def clickOnChildShopping(self):\n '''\n usage : 点击亲子购物\n '''\n API().clickElementByResourceId(self.testcase,\n self.driver,\n self.logger,\n CCPC.resource_id_ll_child_shopping_ll,\n CCPC.click_on_button_timeout)\n\n def clickOnOtherStore(self):\n '''\n usage : 点击其它\n '''\n API().clickElementByResourceId(self.testcase,\n self.driver,\n self.logger,\n CCPC.resource_id_ll_other_store_ll,\n CCPC.click_on_button_timeout)\n\n def validKeywords(self, keywords):\n '''\n usage: 验证关键字\n '''\n API().assertElementByContentDesc(self.testcase,\n self.driver,\n self.logger,\n keywords,\n CCPC.click_on_button_timeout)\n","sub_path":"pages/android/ffan/child_category_page.py","file_name":"child_category_page.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"370744583","text":"from envs.warehouse.components import Warehouse, Forklift, FloorPatch\nimport numpy as np\n\nclass Simulation:\n '''\n This sets up our Environment\n '''\n def __init__(self, X_dim, Y_dim, n_forklifts = 1, joblist_n = 100, task_n = 3):\n self.WAREHOUSE_DIM = X_dim\n self.LAB = [0, Y_dim - 1]\n self.SHIPPING = [X_dim - 1, Y_dim - 1]\n self.RECEIVING = [0,0]\n\n self.forklifts_n = n_forklifts\n self.warehouse = Warehouse(x_dim = X_dim, y_dim = Y_dim, receiving = [0,0], shipping = [X_dim - 1, Y_dim - 1], lab = [0, Y_dim - 1])\n self.locations_n = 3\n #self.forklifts = list(self.__setattr__('Forklift'+str(k), Forklift(start_position = [0,0], job = None)) for k in range(n_forklifts))\n\n self.jobs_n = joblist_n\n self.task_n = task_n\n self.joblist = self._generate_job_list()\n self.buckets = self._make_buckets(self._joblist_to_dict(self.joblist))\n\n self.forklift_names = []\n for k in range(self.forklifts_n):\n self.__setattr__('Forklift'+str(k), Forklift([0,0], []))\n self.forklift_names.append('Forklift'+str(k))\n\n def getJobType(self, job):\n locations = [self.SHIPPING, self.LAB, self.RECEIVING]\n #print('job = ', job)\n if len(job) > 0:\n #print('looking for the job')\n for task in job:\n for i in range(len(locations)):\n #print('{}, {}, types {} and {}'.format(task, locations[i], type(task), type(locations[i])))\n if list(task) == locations[i]:\n return i\n else:\n return None\n\n def getCapacity(self):\n capacities = np.zeros(3)\n '''\n loop over all forklifts and update capacity based on how many\n forklifts are currently assigned to that location\n '''\n\n for name in self.forklift_names: #loop over forklifts\n forklift = self.__getattribute__(name)\n job = forklift.job_list\n #print('getCapacity(): job = ', forklift.job_list)\n try:\n index = self.getJobType(job)\n if capacities[index] < 3:\n capacities[index] += 1\n except:\n continue\n #print('job type = {}'.format(index))\n\n\n #print('cap = {}'.format(capacities))\n\n return capacities\n\n ''' def toGrad(self, obs): #converts\n gradient = [0, self.jobs_n / (self.task_n * 3 * 2), self.jobs_n / self.task_n]\n if obs <= 0:\n obs = 0\n elif obs > 0 and obs <= gradient[1]:\n obs = 1\n elif obs > gradient[1] and obs < gradient[2]:\n obs = 2\n else:\n obs = 3\n return obs'''\n\n\n def toGrad(self, obs): #More memory efficient\n gradient = [0, self.jobs_n / (self.task_n * 3 * 2), self.jobs_n / self.task_n]\n if obs <= 0:\n obs = 0\n elif obs > 0 and obs <= gradient[1]:\n obs = 1\n else:\n obs = 2\n return obs\n\n def getObs(self):\n observation = np.zeros((self.task_n + 1) * 3 + 1) #each (loc, tasklength) pair + capacity of each location (These are set to 3?) + 1 (I forgot, it doesn't get updated)\n locations = ['Shipping', 'Lab', 'Receiving']\n\n for i in range(len(locations)): #update number of jobs left of each type\n for tsk_len in range(self.task_n):\n observation[3*i+tsk_len] = self.toGrad(len(self.buckets[(locations[i], tsk_len+2)]))\n\n capacities = self.getCapacity() #grab capacities and update observation\n start_cap = self.task_n*3\n for i in range(3):\n observation[start_cap+i] = capacities[i]\n\n return observation\n\n\n def getAction(self, action):\n locations = ['Shipping', 'Lab', 'Receiving']\n x = action / self.locations_n\n y = action % self.task_n\n x, y = int(x), int(y) #cast to integers\n action = (locations[x], y+2)\n return action\n\n\n\n def isFeasible(self, action):\n try:\n\n #print(self.buckets[action][0])\n self.buckets[action][0]\n #print('is feasible')\n return True\n except:\n return False\n\n def update(self, time): #updates the simulation, does not update time\n #loop through all forklifts and update their status\n for name in self.forklift_names:\n forklift = self.__getattribute__(name)\n\n #updates a forklift if its time has come\n if forklift.next_update_time <= time:\n #if next location is unoccupied, add this forklift to it and update the next time\n if forklift.status == 'traveling' or forklift.status == 'waiting':\n if self.warehouse.__getattribute__(str(forklift.position)).occupied == 0:\n #print('adding forklif to {}'.format(forklift.position))\n self.warehouse.__getattribute__(str(forklift.position)).add_forklift()\n forklift.update_pick_up_time(time)\n else:\n forklift.status = 'waiting'\n #if it was picking, update its status to next position\n elif forklift.status == 'picking':\n #print('removing forklift at {}'.format(forklift.position))\n self.warehouse.__getattribute__(str(forklift.position)).remove_forklift()\n forklift.update_travel_time(time)\n\n \"\"\"\n Helper functions below\n \"\"\"\n def _joblist_to_dict(self, joblist):\n \"\"\"\n Turn any joblist into a dictionary.\n Key = index\n Tuple[0] = job definition\n Tuple[1] = job destination\n Tuple[3] = job length\n \"\"\"\n joblist_len = len(joblist)\n job_dict={}\n for index in range(joblist_len):\n job_dict[index] = (joblist[index][0], #job definition\n joblist[index][1], #job destination\n len(joblist[index][0])) #job length\n return job_dict\n\n def _make_buckets(self, job_dict):\n \"\"\"\n Turn a job info dictionary into a dictionary bucket such that:\n key = (type('Shipping' etc),job length(int))\n value = [specific jobs]\n \"\"\"\n buckets = {}\n for job_key in job_dict:\n bucket_key = (job_dict[job_key][1],job_dict[job_key][2])\n try:\n buckets[bucket_key].append(job_dict[job_key][0])\n except:\n buckets[bucket_key] = [job_dict[job_key][0]]\n\n #add empty list for any missing buckets\n locations = ['Receiving', 'Shipping', 'Lab']\n mylabels = [(loc, i) for loc in locations for i in range(2, self.task_n+2)]\n for label in mylabels:\n try:\n buckets[label]\n except:\n buckets[label] = []\n\n\n\n return buckets\n\n def _generate_random_job(self):\n \"\"\"\n Returns a job, and the type of the job regarding its\n destination.\n \"\"\"\n WAREHOUSE_DIM = self.WAREHOUSE_DIM\n RECEIVING = self.RECEIVING\n SHIPPING = self.SHIPPING\n LAB = self.LAB\n max_task_length = self.task_n\n\n job_length = 1 + np.random.randint(max_task_length) # number of tasks\n job = np.random.randint(WAREHOUSE_DIM, size=job_length*2)\n for i in range(0,job_length-1):\n while (job[2*i]==RECEIVING[0] and job[2*i+1]==RECEIVING[1]) or \\\n (job[2*i]==SHIPPING[0] and job[2*i+1]==SHIPPING[1]) or \\\n (job[2*i]==LAB[0] and job[2*i+1]==LAB[1]):\n job = np.random.randint(WAREHOUSE_DIM, size=job_length*2)\n destination = [RECEIVING, SHIPPING, LAB][np.random.choice([0,1,2])]\n if destination == RECEIVING: # if assigned receiving\n job = np.insert(job, 0, destination) # put destination in front of job\n job_type = 'Receiving'\n elif destination == SHIPPING:\n job = np.append(job, destination)\n job_type = 'Shipping'\n else:\n job = np.append(job, destination)\n job_type = 'Lab'\n job = job.reshape(job_length + 1, 2)\n return (job, job_type)\n\n def _generate_job_list(self):\n \"\"\"\n Generate a tuple list, with each item in the list representing\n a job, and its type. List length is defined as the joblist length.\n \"\"\"\n tuple_list = [self._generate_random_job() for i in range(self.jobs_n)]\n return tuple_list\n","sub_path":"custom_gym/envs/warehouse/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":8611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"219543521","text":"__author__ = 'aleaf'\n\n#import sys\n#sys.path.append('/Users/aleaf/Documents/GitHub/flopy3')\nimport os\nimport matplotlib\nmatplotlib.use('agg')\nimport flopy\nimport pytest\n\nprint(os.getcwd())\n\nif os.path.split(os.getcwd())[-1] == 'flopy3':\n path = os.path.join('examples', 'data', 'mf2005_test')\nelse:\n path = os.path.join('..', 'examples', 'data', 'mf2005_test')\n\nstr_items = {0: {'mfnam': 'str.nam',\n 'sfrfile': 'str.str'}}\n\ndef test_str_plot():\n\n m = flopy.modflow.Modflow.load(str_items[0]['mfnam'], model_ws=path, verbose=True)\n assert isinstance(m.str.plot()[0], matplotlib.axes.Axes)\n\nif __name__ == '__main__':\n test_str_plot()","sub_path":"autotest/t015_test.py","file_name":"t015_test.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"161122891","text":"def main():\n message = [37,39,29]\n print(decrypt_message(7,11,17,message))\n #print(modular_large_number(667, 937, 2537))\n\n\ndef decrypt_message(p,q,e, encrypted_message):\n n = p*q\n z = (p-1)*(q-1)\n public_key = [n,e]\n #print(public_key)\n d = calculate_modular(n,1,z)\n #print(d)\n private_key = [n, d]\n #print(private_key)\n decrypted_message = \"\"\n for c in encrypted_message:\n m = modular_large_number(c,d,n)\n print(m)\n decrypted_message += chr(m)\n print(m)\n return decrypted_message\n\n\ndef calculate_modular(a,b,n):\n mod = n\n p = []\n x =[]\n p.append(0)\n p.append(1)\n quotient = []\n remainder = []\n\n #print('p0 = ', p[0])\n #print('p1 = ', p[1])\n\n\n while n%a != 0:\n q = n//a\n #print(q)\n r = n%a\n n= a\n a = r\n quotient.append(q)\n remainder.append(r)\n for i in range(len(quotient)):\n p.append(p[i+2-2] - p[i+2-1]*quotient[i])\n while p[i+2] < 0:\n p[i+2] = p[i+2] + mod\n while p[i+2] > mod:\n p[i+2] = p[i+2] - mod\n #print('p', i, ' = ', p[i+2-2], '-', p[i+2-1], '*', quotient[i], ' mod ', mod, ' = ',p[i+2] )\n t = p[len(p)-1]\n return t\n if b > 1:\n d = remainder[len(remainder)-1]\n x.append((p[len(p)-1]*b)//d)\n while x[0] < 0:\n x[0] = x[0] + mod\n while x[0] > mod:\n x[0] = x[0] - mod\n i = -1\n while (x[0] + i*(mod//d)) < mod and (x[0]+i*(mod//d) > 0):\n x.append(x[0] + i*(mod//d))\n i -= 1\n x.sort()\n #print('x = ', x)\n #print('---------------------------------------------------------')\n\n\ndef modular_large_number(a, b, n):\n b_binary = bin(b)\n binary = b_binary[2:]\n list_binary = []\n list_index = []\n list_mod = []\n #print(binary)\n for i in binary:\n list_binary.append(i)\n list_binary.reverse()\n # print(list_binary)\n for j in range(len(list_binary)):\n if int(list_binary[j]) == 1:\n # print(list_binary[j])\n list_index.append(j)\n # print(list_index)\n mod = cal_mod(a, n)\n #print(mod)\n for i in range(len(list_binary)):\n mod = cal_mod(mod, n)\n list_mod.append(mod)\n # print(mod)\n mod = pow(mod, 2)\n # print(list_mod)\n result = 1\n for i in range(len(list_mod)):\n if i in list_index:\n result = int(result * list_mod[i])\n return cal_mod(result, n)\n\n\ndef cal_mod(a, b):\n return a % b\n\n\nmain()","sub_path":"Term 1/SE/PycharmProjects/pythonProject/DMA/phuong.py","file_name":"phuong.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"452835385","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Dmitry Sirenchenko'\n\n\nimport random\nimport numpy\n\nfrom training_data import *\n\n\nclass NeuralNetwork:\n def __init__(self):\n\n #numpy.random.seed(1)\n self.syn_weights_layer1_neuron1 = 2 * numpy.random.random((3, 1)) - 1\n self.syn_weights_layer1_neuron2 = 2 * numpy.random.random((3, 1)) - 1\n self.syn_weights_layer2_neuron1 = 2 * numpy.random.random((2, 1)) - 1\n self.syn_weights_layer2_neuron2 = 2 * numpy.random.random((2, 1)) - 1\n self.syn_weights_layer3_neuron1 = 2 * numpy.random.random((2, 1)) - 1\n self.syn_weights_layer3_neuron2 = 2 * numpy.random.random((2, 1)) - 1\n print('Иницилизация весовых коефициентов: ')\n print(self.syn_weights_layer1_neuron1)\n print(self.syn_weights_layer1_neuron2)\n print(self.syn_weights_layer2_neuron1)\n print(self.syn_weights_layer2_neuron2)\n print(self.syn_weights_layer3_neuron1)\n print(self.syn_weights_layer3_neuron2)\n print('===============================')\n\n #self.list_test_data = DATA1\n\n self.list_test_data = DATA1\n\n # random.shuffle(list_test_data)\n\n self.new_test_data = self.list_test_data[1:]\n self.control_data = self.list_test_data[:2]\n self.new_test_data = self.control_data = self.list_test_data\n\n def __enter__(self):\n return self\n\n def __del__(self):\n print('del')\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n print('TEST MODEL')\n for data in self.control_data:\n train_input = numpy.array([data['input']])\n self.test_model(train_input)\n\n def get_list_data(self):\n return self.list_test_data\n\n def training_on_set(self):\n data = self.new_test_data\n random.shuffle(data)\n for data in data:\n # print(data)\n train_input = numpy.array([data['input']])\n train_output = numpy.array([[data['output']]]).T\n self.train_on_sample(train_input, train_output)\n\n def sigma(self, x):\n return 1 / (1 + numpy.exp(-x))\n\n def train_on_sample(self, train_input, train_output):\n out_layer1_neuron1 = self.sigma(numpy.dot(train_input, self.syn_weights_layer1_neuron1))\n out_layer1_neuron2 = self.sigma(numpy.dot(train_input, self.syn_weights_layer1_neuron2))\n input_layer2_1 = numpy.concatenate(([out_layer1_neuron1.flatten()], [out_layer1_neuron2.flatten()]))\n input_layer2_2 = numpy.concatenate(([out_layer1_neuron1.flatten()], [out_layer1_neuron2.flatten()]))\n\n out_layer2_neuron1 = self.sigma(numpy.dot(input_layer2_1.transpose(), self.syn_weights_layer2_neuron1))\n out_layer2_neuron2 = self.sigma(numpy.dot(input_layer2_2.transpose(), self.syn_weights_layer2_neuron2))\n\n input_layer3_1 = numpy.concatenate(([out_layer2_neuron1.flatten()], [out_layer2_neuron2.flatten()]))\n input_layer3_2 = numpy.concatenate(([out_layer2_neuron1.flatten()], [out_layer2_neuron2.flatten()]))\n\n out_layer3_neuron1 = self.sigma(numpy.dot(input_layer3_1.transpose(), self.syn_weights_layer3_neuron1))\n out_layer3_neuron2 = self.sigma(numpy.dot(input_layer3_2.transpose(), self.syn_weights_layer3_neuron2))\n\n # ============layer3===================\n output3 = numpy.concatenate(([out_layer3_neuron1], [out_layer3_neuron2]))\n error_layer3 = (output3 - train_output) * output3 * (1 - output3)\n new_error_layer3 = numpy.concatenate(([error_layer3[0].flatten()], [error_layer3[1].flatten()]))\n\n weights_layer3 = numpy.concatenate(([self.syn_weights_layer2_neuron1.T], [self.syn_weights_layer2_neuron2.T])).transpose()\n\n gradient_layer3_W21 = out_layer2_neuron2 * -1 * error_layer3[0]\n gradient_layer3_W22 = out_layer2_neuron2 * -1 * error_layer3[1]\n gradient_layer3_W11 = out_layer2_neuron1 * -1 * error_layer3[0]\n gradient_layer3_W12 = out_layer2_neuron1 * -1 * error_layer3[1]\n\n gradient_layer3_neuron1 = numpy.concatenate(\n ([gradient_layer3_W11.flatten()], [gradient_layer3_W21.flatten()]))\n gradient_layer3_neuron2 = numpy.concatenate(\n ([gradient_layer3_W12.flatten()], [gradient_layer3_W22.flatten()]))\n\n # ============layer2===================\n error_layer2_1 = numpy.dot(new_error_layer3.transpose(), weights_layer3[0].T) * out_layer1_neuron1 * (\n 1 - out_layer1_neuron1)\n error_layer2_2 = numpy.dot(new_error_layer3.transpose(), weights_layer3[1].T) * out_layer1_neuron2 * (\n 1 - out_layer1_neuron2)\n new_error_layer2 = numpy.concatenate(([error_layer2_1.flatten()], [error_layer2_2.flatten()]))\n\n weights_layer2 = numpy.concatenate(([self.syn_weights_layer2_neuron1.T], [self.syn_weights_layer2_neuron2.T])).transpose()\n\n gradient_layer2_W21 = out_layer1_neuron2 * -1 * error_layer3[0]\n gradient_layer2_W22 = out_layer1_neuron2 * -1 * error_layer3[1]\n gradient_layer2_W11 = out_layer1_neuron1 * -1 * error_layer3[0]\n gradient_layer2_W12 = out_layer1_neuron1 * -1 * error_layer3[1]\n\n gradient_layer2_neuron1 = numpy.concatenate(\n ([gradient_layer2_W11.flatten()], [gradient_layer2_W21.flatten()]))\n gradient_layer2_neuron2 = numpy.concatenate(\n ([gradient_layer2_W12.flatten()], [gradient_layer2_W22.flatten()]))\n\n # ==========layer1=====================\n\n error_layer1_neuron1 = numpy.dot(new_error_layer2.transpose(), weights_layer2[0].T) * out_layer1_neuron1 * (\n 1 - out_layer1_neuron1)\n error_layer1_neuron2 = numpy.dot(new_error_layer2.transpose(), weights_layer2[1].T) * out_layer1_neuron2 * (\n 1 - out_layer1_neuron2)\n\n\n\n gradient_layer1_neuron1 = (train_input * -1 * error_layer1_neuron1).T\n gradient_layer1_neuron2 = (train_input * -1 * error_layer1_neuron2).T\n\n\n # Update synaptic weights\n self.syn_weights_layer1_neuron1 = gradient_layer1_neuron1 + self.syn_weights_layer1_neuron1\n self.syn_weights_layer1_neuron2 = gradient_layer1_neuron2 + self.syn_weights_layer1_neuron2\n\n self.syn_weights_layer2_neuron1 = gradient_layer2_neuron1 + self.syn_weights_layer2_neuron1\n self.syn_weights_layer2_neuron2 = gradient_layer2_neuron2 + self.syn_weights_layer2_neuron2\n\n self.syn_weights_layer3_neuron1 = gradient_layer3_neuron1 + self.syn_weights_layer3_neuron1\n self.syn_weights_layer3_neuron2 = gradient_layer3_neuron2 + self.syn_weights_layer3_neuron2\n\n #print('new weights')\n #print(self.syn_weights_layer1_neuron1)\n #print(self.syn_weights_layer1_neuron2)\n #exit()\n\n\n def test_model(self, input):\n out_layer1_neuron1 = self.sigma(numpy.dot(input, self.syn_weights_layer1_neuron1))\n out_layer1_neuron2 = self.sigma(numpy.dot(input, self.syn_weights_layer1_neuron2))\n input_layer2_1 = numpy.concatenate(([out_layer1_neuron1.flatten()], [out_layer1_neuron2.flatten()]))\n input_layer2_2 = numpy.concatenate(([out_layer1_neuron1.flatten()], [out_layer1_neuron2.flatten()]))\n\n out_layer2_neuron1 = self.sigma(numpy.dot(input_layer2_1.transpose(), self.syn_weights_layer2_neuron1))\n out_layer2_neuron2 = self.sigma(numpy.dot(input_layer2_2.transpose(), self.syn_weights_layer2_neuron2))\n\n input_layer3_1 = numpy.concatenate(([out_layer2_neuron1.flatten()], [out_layer2_neuron2.flatten()]))\n input_layer3_2 = numpy.concatenate(([out_layer2_neuron1.flatten()], [out_layer2_neuron2.flatten()]))\n\n out_layer3_neuron1 = self.sigma(numpy.dot(input_layer3_1.transpose(), self.syn_weights_layer3_neuron1))\n out_layer3_neuron2 = self.sigma(numpy.dot(input_layer3_2.transpose(), self.syn_weights_layer3_neuron2))\n\n output3 = numpy.concatenate(([out_layer3_neuron1], [out_layer3_neuron2]))\n print(input[0], end=' ')\n print(round((output3[0][0][0]), 2), end=' ')\n print(round((output3[1][0][0]), 2), end='\\n')\n #print(output[0][0][0], end='\\t')\n #print(output[1][0][0])\n #print('----------------------------')\n\n\nif __name__ == '__main__':\n with NeuralNetwork() as NN:\n for i in range(1, 30000):\n NN.training_on_set()\n print(i)\n","sub_path":"first_NN.py","file_name":"first_NN.py","file_ext":"py","file_size_in_byte":8365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"451904188","text":"class Ip:\n def Gw(gw, option):\n if(option == 'client'):\n seletor = '/list/client'\n if(option == 'service'):\n seletor = '/list/service'\n if(option == 'data'):\n seletor = '/list/data'\n if(option == 'addClient'):\n seletor = '/client'\n if(option == 'addService'):\n seletor = '/service'\n if(option == 'addData'):\n seletor = '/data'\n if(gw == 'cloud'):\n gateway = 'https://uiot-dims.herokuapp.com'\n if(gw == 'local'):\n gateway = 'http://localhost:5000'\n return gateway + seletor\n #https://uiot-dims.herokuapp.com\n\n def Mac():\n return '02:02:02:02'\n\n","sub_path":"orquestrador/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"36699656","text":"# %% [markdown]\n# # 📃 Solution for Exercise 02\n#\n# The aim of this exercise it to explore some attributes available in\n# scikit-learn random forest.\n#\n# First, we will fit the penguins regression dataset.\n\n# %%\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv(\"../datasets/penguins_regression.csv\")\nfeature_names = [\"Flipper Length (mm)\"]\ntarget_name = \"Body Mass (g)\"\nX, y = data[feature_names], data[target_name]\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n# %% [markdown]\n# Create a random forest containing only three trees. Train the forest and\n# check the performance on the testing set.\n\n# %%\nfrom sklearn.ensemble import RandomForestRegressor\n\nforest = RandomForestRegressor(n_estimators=3)\nforest.fit(X_train, y_train)\nprint(f\"Accuracy score: {forest.score(X_test, y_test):.3f}\")\n\n# %% [markdown]\n# The forest that you created contains three trees that can be accessed with\n# the attribute `estimators_`. You will have to:\n#\n# - create a new dataset containing flipper length between 170 mm and 230 mm;\n# - plot the training data using a scatter plot;\n# - plot the decision of each individual tree by predicting on the newly\n# created dataset;\n# - plot the decision of the random forest using this newly created dataset.\n\n# %%\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nsns.set_context(\"talk\")\n\nX_ranges = pd.DataFrame(\n np.linspace(X.iloc[:, 0].min(), X.iloc[:, 0].max(), num=300),\n columns=X.columns,\n)\n\n_, ax = plt.subplots(figsize=(8, 6))\n\nsns.scatterplot(\n data=data, x=feature_names[0], y=target_name, color=\"black\", alpha=0.5\n)\nfor tree_idx, tree in enumerate(forest.estimators_):\n ax.plot(\n X_ranges,\n tree.predict(X_ranges),\n label=f\"Tree #{tree_idx}\",\n linestyle=\"--\",\n )\nax.plot(X_ranges, forest.predict(X_ranges), label=f\"Random forest\")\n_ = ax.legend()\n\n# %%\n","sub_path":"python_scripts/ensemble_sol_02.py","file_name":"ensemble_sol_02.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"279835538","text":"import pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\na3_q7 = pd.read_csv('a3_q7.csv')\na3_q7_numpy = a3_q7.to_numpy()\nD = a3_q7_numpy\nx_array = np.arange(start=-0.01, stop=1.01, step=0.01)\nh_array = [0.0001, 0.0005, 0.001, 0.005, 0.05]\n\n\ndef ker(u):\n if(u <= 1 and u >= -1):\n return 0.5\n else:\n return 0\n\n\ndef uniform_kde(x, h, D):\n sum_k = 0\n for points in D:\n u = (x-points[1])/h\n sum_k = sum_k + ker(u)\n\n return sum_k/(len(D)*h)\n\n\nfor i in range(len(h_array)):\n y = []\n for x in x_array:\n y.append(uniform_kde(x, h_array[i], D))\n tag = \"h = \"+str(h_array[i])\n plt.plot(x_array, y,label=tag)\n plt.xlabel(\"X-axis\")\n plt.ylabel(\"Y-axis\")\n plt.legend(bbox_to_anchor=(1.1, 1.05))\n plt.show()","sub_path":"Assignment 3/.ipynb_checkpoints/uniform_kde-checkpoint.py","file_name":"uniform_kde-checkpoint.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"231351446","text":"#Write a Python program to remove an empty tuple(s) from a list of tuples.\n#Sample data: [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]\n#Expected output: [('',), ('a', 'b'), ('a', 'b', 'c'), 'd']\n \ntuple= [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]\nprint(\"Tuple Before\",tuple)\ntuple1=[]\nfor new in tuple:\n if new:\n tuple1.append(new)\n \nprint(\"Tuple after\",tuple1) \n","sub_path":"no.12.py","file_name":"no.12.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"571001961","text":"from django.test import TestCase\n\nfrom library.models import Book, User\n\n\nclass UserModelTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n user = User.objects.create_user(\n username='Test',\n email='test@test.te',\n password='password'\n )\n\n def test_user_db_table(self):\n user = User.objects.get(username='Test')\n db_table = user._meta.db_table\n self.assertEquals(db_table, 'library_user')\n\n\nclass BookModelTest(TestCase):\n @classmethod\n def setUpTestData(cls):\n user = User.objects.create_user(\n username='Test',\n email='test@test.te',\n password='password'\n )\n Book.objects.create(\n name='Big',\n author='Bob',\n pages=10,\n price=0,\n user=user\n )\n\n def test_name_label(self):\n book = Book.objects.get(id=1)\n field_label = book._meta.get_field('name').verbose_name\n self.assertEquals(field_label, 'Название')\n\n def test_name_max_length(self):\n book = Book.objects.get(id=1)\n max_length = book._meta.get_field('name').max_length\n self.assertEquals(max_length, 255)\n\n def test_author_label(self):\n book = Book.objects.get(id=1)\n field_label = book._meta.get_field('author').verbose_name\n self.assertEquals(field_label, 'Автор')\n\n def test_author_max_length(self):\n book = Book.objects.get(id=1)\n max_length = book._meta.get_field('author').max_length\n self.assertEquals(max_length, 255)\n\n def test_created_date_label(self):\n book = Book.objects.get(id=1)\n field_label = book._meta.get_field('created_date').verbose_name\n self.assertEquals(field_label, 'Дата создания')\n\n def test_updated_date_label(self):\n book = Book.objects.get(id=1)\n field_label = book._meta.get_field('updated_date').verbose_name\n self.assertEquals(field_label, 'Дата изменения')\n\n def test_pages_label(self):\n book = Book.objects.get(id=1)\n field_label = book._meta.get_field('pages').verbose_name\n self.assertEquals(field_label, 'Количество страниц')\n\n def test_object_name_is_book_name_dash_author_bracket_price_bracket(self):\n book = Book.objects.get(id=1)\n expected_object_name = f'{book.name} - {book.author} ({book.price})'\n self.assertEquals(expected_object_name, str(book))\n","sub_path":"backend/api/library/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"515562604","text":"#!/usr/bin/env python3\n\n#uw python 210\n#lesson04\n#max anderson\n\n#file lab\n\nif __name__ == \"__main__\":\n\n import pathlib\n import os\n import io\n\n #pth = pathlib.Path('./')\n\n # print(pth.absolute())\n\n lst = os.listdir()\n pth = os.getcwd()\n\n for file in lst:\n print(f'{pth}\\\\{file}')\n\n with open('secrets.txt', 'r') as instream:\n with open('secrets2.txt', 'w+') as outstream:\n line = instream.read()\n outstream.write(line)\n\n instream = open()","sub_path":"students/mxwllndrsn/lesson04/file_lab.py","file_name":"file_lab.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"446071419","text":"# Sarus\n#\n# Copyright (c) 2018-2021, ETH Zurich. All rights reserved.\n#\n# Please, refer to the LICENSE file in the root directory.\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport unittest\nimport subprocess\nimport os\nimport json\nimport re\n\nimport common.util as util\n\n\nclass TestHookStdoutStderr(unittest.TestCase):\n \"\"\"\n This test checks that a hook can successfully log messages to stdout and stderr.\n \"\"\"\n\n _OCIHOOK_CONFIG_FILE = os.environ[\"CMAKE_INSTALL_PREFIX\"] + \"/etc/hooks.d/stdout_stderr_test.json\"\n\n @classmethod\n def setUpClass(cls):\n util.pull_image_if_necessary(is_centralized_repository=False, image=\"quay.io/ethcscs/alpine:latest\")\n cls._enable_hook()\n\n @classmethod\n def tearDownClass(cls):\n cls._disable_hook()\n\n @classmethod\n def _enable_hook(cls):\n # create OCI hook's config file\n hook = dict()\n hook[\"version\"] = \"1.0.0\"\n hook[\"hook\"] = dict()\n hook[\"hook\"][\"path\"] = os.environ[\"CMAKE_INSTALL_PREFIX\"] + \"/bin/stdout_stderr_test_hook\"\n hook[\"when\"] = {\"always\": True}\n hook[\"stages\"] = [\"prestart\"]\n\n with open(\"hook_config.json.tmp\", 'w') as f:\n f.write(json.dumps(hook))\n\n subprocess.check_output([\"sudo\", \"mv\", \"hook_config.json.tmp\", cls._OCIHOOK_CONFIG_FILE])\n subprocess.check_output([\"sudo\", \"chown\", \"root:root\", cls._OCIHOOK_CONFIG_FILE])\n subprocess.check_output([\"sudo\", \"chmod\", \"644\", cls._OCIHOOK_CONFIG_FILE])\n\n @classmethod\n def _disable_hook(cls):\n subprocess.call([\"sudo\", \"rm\", cls._OCIHOOK_CONFIG_FILE])\n\n def test_stdout(self):\n # DEBUG log level\n expected = [\n r\"^hook's stdout$\",\n r\"^\\[\\d+.\\d+\\] \\[.+\\] \\[stdout_stderr_test_hook\\] \\[DEBUG\\] hook's DEBUG log message$\",\n r\"^\\[\\d+.\\d+\\] \\[.+\\] \\[stdout_stderr_test_hook\\] \\[INFO\\] hook's INFO log message$\",\n ]\n stdout = self._get_sarus_stdout(\"--debug\")\n self._check_output_matches(stdout, expected)\n\n # INFO log level\n expected = [\n r\"^hook's stdout$\",\n r\"^\\[\\d+.\\d+\\] \\[.+\\] \\[stdout_stderr_test_hook\\] \\[INFO\\] hook's INFO log message$\",\n ]\n stdout = self._get_sarus_stdout(\"--verbose\")\n self._check_output_matches(stdout, expected)\n\n # WARNING log level\n expected = [\n r\"^hook's stdout$\",\n ]\n stdout = self._get_sarus_stdout()\n self._check_output_matches(stdout, expected)\n\n def test_stderr(self):\n expected = [\n r\"^hook's stderr$\",\n r\"^\\[\\d+.\\d+\\] \\[.+\\] \\[stdout_stderr_test_hook\\] \\[WARN\\] hook's WARN log message$\",\n r\"^\\[\\d+.\\d+\\] \\[.+\\] \\[stdout_stderr_test_hook\\] \\[ERROR\\] hook's ERROR log message$\",\n ]\n stderr = self._get_sarus_stderr()\n self._check_output_matches(stderr, expected)\n\n def _get_sarus_stdout(self, verbose_option=None):\n command = [\"sarus\", \"run\", \"quay.io/ethcscs/alpine:latest\", \"true\"]\n if verbose_option is not None:\n command = command[0:1] + [verbose_option] + command[1:]\n stdout = subprocess.check_output(command).decode()\n return stdout.rstrip().split('\\n') # remove trailing whitespaces\n\n def _get_sarus_stderr(self):\n command = [\"sarus\", \"run\", \"quay.io/ethcscs/alpine:latest\", \"true\"]\n with open(os.devnull, 'wb') as devnull:\n proc = subprocess.run(command,\n stdout=devnull,\n stderr=subprocess.PIPE)\n assert proc.returncode == 0, \"An error occurred while executing Sarus\"\n\n return proc.stderr.decode().rstrip().split('\\n')\n\n def _check_output_matches(self, actuals, expecteds):\n assert len(expecteds) > 0\n i = 0\n\n for actual in actuals:\n if re.match(expecteds[i], actual):\n i += 1\n if i == len(expecteds):\n return\n\n message = \"Expression '\" + expecteds[i] + \"' didn't match any line in Sarus's output:\\n\\n\" + str(actuals)\n assert False, message\n","sub_path":"CI/src/integration_tests/test_hook_stdout_stderr.py","file_name":"test_hook_stdout_stderr.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"436589029","text":"from gensim.models import KeyedVectors\nimport gensim\nimport pickle\nfrom app import logging\n\nNORN_WORD_LIST = [\n '名詞-一般',\n '名詞-固有'\n]\n\n# return nornlist :[str]\ndef tokenize(mecab, input):\n lineList = mecab.parse(input).split('\\n')\n nornList = [line.split('\\t')[0] for line in lineList if '\\t' in line and includeWordList(line.split('\\t')[3], NORN_WORD_LIST)]\n return nornList\n\n\n# return :bool\ndef includeWordList(word, wordList):\n isInclude = [ w in word for w in wordList ]\n return sum(isInclude) > 0\n \n\n# return category_id: int\ndef categorize(model, category_ids, vectors, word):\n try: \n vector = model.get_vector(word)\n maxIndex = model.cosine_similarities(vector, vectors).argmax()\n return category_ids[maxIndex]\n except KeyError:\n logging.warning(\"word {} is not in vocabulary\")\n\n","sub_path":"word2vec/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"238659219","text":"\"\"\"\nMerge two sorted arrays and return it as a new array.\n# NOTE: YOU CAN NOT USE ANY SORTING LIBRARIES\n\"\"\"\n\n\ndef merge_two_list_helper(list1, list2):\n a = list1\n b = list2\n new_list = []\n\n while a and b:\n if a[0] <= b[0]:\n new_list.append(a[0])\n del a[0]\n else:\n new_list.append(b[0])\n del b[0]\n\n new_list.extend(a)\n new_list.extend(b)\n \n return new_list\n \n\n\n# DO NOT CHANGE THIS FUNCTION\ndef merge_two_list(list1, list2):\n\treturn merge_two_list_helper(list1, list2)\n\n\n# test cases\ndef main():\n list1 = [1,3,5]\n list2 = [2,4,6]\n print(\"merging [1,3,5] and [2,4,6]......\")\n print(\"expected result is [1,2,3,4,5,6]\")\n print(\"your output is {}\".format(merge_two_list(list1, list2)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"problem_4/Fellow Codes Go Here/tom_soare.py","file_name":"tom_soare.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"220842065","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nEntrainement de WaveNet - ENSAI 2020\nAuthor : BERNARD Renan\n\nCe fichier .py execute l'entrainement du reseau WaveNet.\n\"\"\"\n\nfrom keras.callbacks import ModelCheckpoint\n\nfrom model import build_wavenet_model\nfrom generator import DataGenerator\n\nEXPERIMENT_NAME = \"exp1\"\nTRAIN_PATH = \"./Data/Train/\"\nVALID_PATH = \"./Data/Validation/\"\nINPUT_SIZE = 4096\nNUM_FILTERS = 16\nKERNEL_SIZE = 2\nNUM_RESIDUAL_BLOCKS = 9\nBATCH_SIZE = 256\nEPOCHS = 20\nFILE_PREDICT_CALLBACK = \"./Data/Validation/14.npy\"\n\ncheckpoint_path = \"weights_\" + EXPERIMENT_NAME + \".hdf5\"\n\ncheckpoint = ModelCheckpoint(\n checkpoint_path,\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n mode='auto',\n period=1)\n\nprint(\"Building model...\")\nmodel = build_wavenet_model(\n input_size=INPUT_SIZE,\n num_filters=NUM_FILTERS,\n kernel_size=KERNEL_SIZE,\n num_residual_blocks=NUM_RESIDUAL_BLOCKS)\nprint(\"OK...\")\n\ntraining_generator = DataGenerator(\n path_to_files=TRAIN_PATH,\n batch_size=BATCH_SIZE,\n dim=(INPUT_SIZE, 1),\n n_classes=256,\n shuffle=True)\n\nvalidation_generator = DataGenerator(\n path_to_files=VALID_PATH,\n batch_size=BATCH_SIZE,\n dim=(INPUT_SIZE, 1),\n n_classes=256,\n shuffle=True)\n\nmodel.fit_generator(\n generator=training_generator, \n validation_data=validation_generator,\n use_multiprocessing=True,\n workers=4,\n epochs=EPOCHS,\n verbose=1,\n callbacks=[checkpoint])\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"2892412","text":"from Bio import Entrez\nimport types\nimport json\nimport pdb\nfrom os import path\nfrom wordcloud import WordCloud\n\nEntrez.email = 'huanghesong3231@yahoo.com'\nlist_json=[]\nlist_txt=[]\n\ndef get_json():\n with open('title.json') as json_file:\n data = json.load(json_file) #list\n for m in data:\n m = m.replace(\"title={\",\"\")\n m = m.replace(\"},\",\"\")\n m = m.strip()\n list_json.append(m)\n \ndef search(query):\n handle = Entrez.esearch(db='pubmed',\n sort='relevance',\n retmax='1',\n retmode='xml',\n term=query)\n results= Entrez.read(handle)\n list=results.get('IdList') \n str = ''.join(list)\n return str\n \ndef getkeywords(id_number):\n file = open('constitution.txt', 'w')\n handle = Entrez.efetch(db=\"pubmed\", id=id_number,rettype=\"abstract\", retmode=\"xml\")\n a=handle.read()\n b=a.split(\"\\n\")\n for c in b:\n if \"Keyword MajorTopicYN\" in c: #string\n c = c.replace('',\"\")\n c = c.replace(\"\",\"\")\n list_txt.append(c)\n str_change = ''.join(list_txt)\n file.write(str_change)\n file.close()\n \n \n\nif __name__==\"__main__\":\n get_json()\n for i in list_json:\n str = search(i)\n getkeywords(str)\n d = path.dirname(__file__)\n text = open(path.join(d, 'constitution.txt')).read()\n wordcloud = WordCloud().generate(text)\n import matplotlib.pyplot as plt\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n wordcloud = WordCloud(max_font_size=40).generate(text)\n plt.figure()\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.show()\n","sub_path":"Pubmed_searchkeywords.py","file_name":"Pubmed_searchkeywords.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"139897661","text":"import errno\nimport logging\nimport os\nimport sys\nfrom threading import Lock\nimport time\nfrom functools import wraps\n\nimport zmq\n\nfrom circus.controller import Controller\nfrom circus.exc import AlreadyExist\nfrom circus.flapping import Flapping\nfrom circus import logger\nfrom circus.show import Show\nfrom circus.util import debuglog\n\n\nclass Trainer(object):\n \"\"\"Class used to control a list of shows.\n\n Options:\n\n - **shows**: a list of Show objects\n - **endpoint**: the controller ZMQ endpoint\n - **pubsub_endpoint**: the pubsub endpoint\n - **check_delay**: the delay between two controller points (defaults: 1 s)\n - **prereload_fn**: callable that will be executed on each reload (defaults:\n None)\n \"\"\"\n def __init__(self, shows, endpoint, pubsub_endpoint, check_delay=1.,\n prereload_fn=None):\n self.shows = shows\n self.endpoint = endpoint\n self.check_delay = check_delay\n self.prereload_fn = prereload_fn\n self.pubsub_endpoint = pubsub_endpoint\n self.context = zmq.Context()\n\n self.ctrl = Controller(self.context, endpoint, self, self.check_delay)\n\n self.pid = os.getpid()\n self._shows_names = {}\n self.alive = True\n self._lock = Lock()\n self._setup()\n logger.info(\"Starting master on pid %s\" % self.pid)\n\n def _setup(self):\n # set pubsub endpoint\n self.pubsub_io = self.context.socket(zmq.PUB)\n self.pubsub_io.bind(self.pubsub_endpoint)\n\n for show in self.shows:\n self._shows_names[show.name.lower()] = show\n show.pubsub_io = self.pubsub_io\n\n def start_flapping(self):\n self.flapping = Flapping(self.endpoint, self.pubsub_endpoint,\n self.check_delay)\n self.flapping.start()\n\n\n @debuglog\n def start(self):\n \"\"\"Starts all the shows.\n\n The start command is an infinite loop that waits\n for any command from a client and that watches all the\n flies and restarts them if needed.\n \"\"\"\n\n # start flapping\n self.start_flapping()\n\n # launch flies\n for show in self.shows:\n show.manage_flies()\n\n while self.alive:\n # manage and reap flies\n for show in self.shows:\n show.reap_flies()\n show.manage_flies()\n\n if not self.flapping.is_alive():\n # flapping is dead, relaunch it.\n self.start_flapping()\n\n # wait for the controller\n self.ctrl.poll()\n\n @debuglog\n def stop(self, graceful=True):\n \"\"\"Stops all shows and their flies.\n\n Options:\n\n - **graceful**: sends a SIGTERM to every fly and waits a bit\n before killing it (default: True)\n \"\"\"\n if not self.alive:\n return\n\n self.alive = False\n\n self.flapping.stop()\n\n # kill flies\n for show in self.shows:\n show.stop(graceful=graceful)\n\n time.sleep(0.5)\n try:\n self.context.destroy(0)\n except zmq.ZMQError as e:\n if e.errno == errno.EINTR:\n pass\n else:\n raise\n\n @debuglog\n def reload(self):\n \"\"\"Reloads everything.\n\n Run the :func:`prereload_fn` callable if any, then gracefuly\n reload all shows.\n \"\"\"\n if self.prereload_fn is not None:\n self.prereload_fn(self)\n\n # reopen log files\n for handler in logger.handlers:\n if isinstance(handler, logging.FileHandler):\n handler.acquire()\n handler.stream.close()\n handler.stream = open(handler.baseFilename,\n handler.mode)\n handler.release()\n\n # gracefully reload shows\n for show in self.shows:\n show.reload()\n\n def numflies(self):\n \"\"\"Return the number of flies running across all shows.\"\"\"\n return sum([len(show) for show in self.shows])\n\n def num_shows(self):\n \"\"\"Return the number of shows.\"\"\"\n return len(self.shows)\n\n def get_show(self, name):\n \"\"\"Return the show *name*.\"\"\"\n return self._shows_names[name]\n\n def add_show(self, name, cmd):\n \"\"\"Adds a show.\n\n Options:\n\n - **name**: name of the show to add\n - **cmd**: command to run.\n \"\"\"\n with self._lock:\n if name in self._shows_names:\n raise AlreadyExist(\"%r already exist\" % show.name)\n\n show = Show(name, cmd, stopped=True)\n show.pubsub_io = self.pubsub_io\n self.shows.append(show)\n self._shows_names[show.name.lower()] = show\n\n def del_show(self, name):\n \"\"\"Deletes a show.\n\n Options:\n\n - **name**: name of the show to delete\n \"\"\"\n logger.debug('Deleting %r show' % name)\n\n with self._lock:\n # remove the show from the list\n show = self._shows_names.pop(name)\n del self.shows[self.shows.index(show)]\n\n # stop the show\n show.stop()\n\n ###################\n # commands\n ###################\n\n @debuglog\n def handle_stop(self):\n self.stop()\n handle_quit = handle_stop\n\n @debuglog\n def handle_terminate(self):\n self.stop(graceful=False)\n\n @debuglog\n def handle_numflies(self):\n return str(self.numflies())\n\n @debuglog\n def handle_numshows(self):\n return str(self.num_shows())\n\n @debuglog\n def handle_shows(self):\n return \",\".join(self._shows_names.keys())\n\n @debuglog\n def handle_flies(self):\n flies = []\n for show in self.shows:\n flies.append(\"%s: %s\" % (show.name, show.handle_flies()))\n return buffer(\"\\n\".join(flies))\n\n @debuglog\n def handle_info_shows(self):\n infos = []\n for show in self.shows:\n infos.append(\"%s:\\n\" % show.name)\n infos.append(\"%s\\n\" % show.handle_info())\n return buffer(\"\".join(infos))\n\n @debuglog\n def handle_reload(self):\n self.reload()\n return \"ok\"\n\n @debuglog\n def handle_add_show(self, name, cmd):\n self.add_show(name, cmd)\n return \"ok\"\n\n @debuglog\n def handle_del_show(self, name):\n self.del_show(name)\n return \"ok\"\n\n @debuglog\n def handle_stop_shows(self):\n for show in self.shows:\n show.stop()\n return \"ok\"\n\n @debuglog\n def handle_start_shows(self):\n for show in self.shows:\n show.start()\n return \"ok\"\n\n @debuglog\n def handle_restart_shows(self):\n for show in self.shows:\n show.restart()\n return \"ok\"\n","sub_path":"circus/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":6744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"313068379","text":"# coding: utf-8\n# __getattr__ 就是在查找不到属性的时候调用\n# __getattribute__\nfrom datetime import date\n\n\nclass User:\n def __init__(self, name, birthday):\n self.name = name\n self.birthday = birthday\n\n def __getattr__(self, item):\n print(('not find attr'))\n\n\nif __name__ == \"__main__\":\n user = User('bobby', date(year=1987, month=1, day=1))\n print(user.age)\n","sub_path":"chapter08/getattr.py","file_name":"getattr.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"97780131","text":"'''\n@Description: \n@Author: Zhaoxi Chen\n@Github: https://github.com/FrozenBurning\n@Date: 2020-03-14 14:28:17\n@LastEditors: Zhaoxi Chen\n@LastEditTime: 2020-03-14 15:34:03\n'''\nimport cv2\nimport numpy as np\nimport keras\nimport math\n#import tensorflow as tf\n#from tensorflow.python.keras.utils.data_utils import Sequence\nclass DataGenerator(keras.utils.Sequence):\n \n def __init__(self, datas, labels,nClasses=21,batch_size=32, shuffle=True,input_shape=[224,224],output_shape=[224,224]):\n self.batch_size = batch_size\n self.datas = datas\n self.labels = labels\n self.indexes = np.arange(len(self.datas))\n self.shuffle = shuffle\n self.input_width = input_shape[0]\n self.input_height = input_shape[1]\n self.output_width = output_shape[0]\n self.output_height = output_shape[1]\n self.nClasses = nClasses\n\n def __len__(self):\n return math.ceil(len(self.datas) / float(self.batch_size))\n\n def __getitem__(self, idx):\n\n batch_indexs = self.indexes[idx*self.batch_size:(idx+1)*self.batch_size]\n batch_datas = [self.datas[k] for k in batch_indexs]\n batch_labels = [self.labels[k] for k in batch_indexs]\n #batch_datas = self.datas[idx * self.batch_size:(idx + 1)*self.batch_size]\n #batch_labels = self.labels[idx * self.batch_size:(idx + 1)*self.batch_size]\n X, y = self.data_generation(batch_datas,batch_labels)\n #print('get item!')\n \n return X,y\n\n def on_epoch_end(self):\n if self.shuffle == True:\n np.random.shuffle(self.indexes)\n\n def data_generation(self, batch_datas,batch_labels):\n images = []\n labels = []\n\n for im ,seg in zip(batch_datas,batch_labels) :\n images.append(getImageArr(im, self.input_width , self.input_height))\n labels.append(getSegmentationArr(seg, self.nClasses , self.output_width , self.output_height))\n \n return np.array(images), np.array(labels)\n\n\n\ndef getImageArr( path , width , height ):\n img = cv2.imread(path, 1)\n img = np.float32(cv2.resize(img, ( width , height ))) /127.5-1\n return img\n\ndef getSegmentationArr( path , nClasses , width , height ):\n\n seg_labels = np.zeros(( height , width , nClasses ))\n img = cv2.imread(path, 1)\n img = cv2.resize(img, ( width , height ))\n img = img[:, : , 0]\n\n for c in range(nClasses):\n seg_labels[: , : , c ] = (img == c ).astype(int)\n ##seg_labels = np.reshape(seg_labels, ( width*height,nClasses ))\n return seg_labels\n\ndef read_data_path(root='/home/throne/data/VOCdevkit/VOC2012',extension='/list/trainval_aug.txt', train=True):\n txt_fname = root + extension\n with open(txt_fname, 'r') as f:\n images = f.read().splitlines()\n print(len(images))\n data = [root+i.split()[0] for i in images]\n label = [root+i.split()[1] for i in images]\n return data, label\n\ndef divider(X,y,train_rate=0.85):\n index_train = np.random.choice(len(X),int(len(X)*train_rate),replace=False)\n index_test = list(set(range(len(X))) - set(index_train))\n X_train, y_train = np.array(X)[index_train],np.array(y)[index_train]\n X_test, y_test = np.array(X)[index_test],np.array(y)[index_test]\n return X_train,y_train,X_test,y_test\n\ndef path2data(X,y,input_width=224,input_height=224,output_width=224,output_height=224):\n X_data=[]\n y_label=[]\n for im,seg in zip(X,y) :\n X_data.append(getImageArr(im , input_width , input_height))\n y_label.append(getSegmentationArr(seg , 21 , output_width , output_height))\n return np.array(X_data),np.array(y_label)\n","sub_path":"utils/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"597468120","text":"'''\nCreated on 2016. 8. 15.\n\n@author: dennis\n'''\n\nimport datetime\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render\nfrom .models import ContactUs\n\ndef contact_us(request):\n if request.method == 'POST':\n contactUs = ContactUs()\n \n contactUs.category = request.POST.get('category')\n contactUs.name = request.POST.get('name')\n contactUs.phone = request.POST.get('phone')\n contactUs.email = request.POST.get('email')\n contactUs.message = request.POST.get('message')\n contactUs.received = datetime.datetime.now()\n contactUs.save();\n \n return HttpResponse(\n )\n else:\n return HttpResponse()\n \n\ndef login_dlg(request):\n return render(request, \"login_dlg.tmpl.html\", {})\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"282470662","text":"#Sebastian Macias Ibarra - A01376492\r\n#Msion 10\r\n\r\n#librerias\r\nimport matplotlib.pyplot as plot\r\n\r\n#1. Muestra los nombres de los equipos en mayúsculas ordenados alfabeticamente\r\ndef ordenarNombresAlfabeticamente(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n listaNombres = []\r\n\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n for linea in entrada:\r\n #linea = 'Necaxa&16&3&5&8&19&28&-9&14'\r\n datos = linea.split(\"&\") # ['Necaxa', '16', ...]\r\n nombresEquipo = datos[0]\r\n nombresEquipo = str.upper(nombresEquipo)\r\n listaNombres.append(nombresEquipo)\r\n listaNombres.sort()\r\n\r\n entrada.close()\r\n\r\n return listaNombres\r\n\r\n\r\n#2.Regresa un diccionario con los nombres y los puntos actuales\r\ndef crearRelacionNombresYPuntos(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n listaNombresPuntos = []\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n\r\n for linea in entrada:\r\n # linea = 'Necaxa&16&3&5&8&19&28&-9&14'\r\n datos = linea.split(\"&\")\r\n nombreEquipo = datos[0]\r\n puntos = int(datos[8])\r\n listaNombresPuntos.append((nombreEquipo, puntos))\r\n\r\n entrada.close()\r\n\r\n return listaNombresPuntos\r\n\r\n\r\n#3.Regresa una lista que contiene los equipos con 3 o menos partidos perdidos\r\ndef mostrarEquipos_MenosPartidosPerdidos(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n listaEquipos = []\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n\r\n for linea in entrada:\r\n datos = linea.split(\"&\")\r\n nombreEquipo = datos[0]\r\n jPerdidos = int(datos[4])\r\n\r\n if jPerdidos <= 3:\r\n listaEquipos.append(nombreEquipo)\r\n\r\n entrada.close()\r\n\r\n return listaEquipos\r\n\r\n#4. Buscar en el archivo, quipos que tienen mal reportada su cantidad de puntos\r\ndef buscarEquiposError(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n equipos = []\r\n entrada.readline() #Título 1\r\n entrada.readline() #Título 2\r\n\r\n #Realizamos un ciclo para visitar lso datos del archivo\r\n for linea in entrada:\r\n #linea = 'Necaxa&16&3&5&8&19&28&-9&14'\r\n datos = linea.split(\"&\") # ['Necaxa', '16', ...]\r\n nombreEquipo = datos[0]\r\n jGanados = int(datos[2])\r\n jEmpatados = int(datos[3])\r\n ptsReportados = int(datos[8])\r\n\r\n puntos = jGanados * 3 + jEmpatados #Se multiplican los puntos de los partidos ganado por la cantidad y luego se le suman los puntos de los juegos cempatados\r\n if puntos != ptsReportados:\r\n equipos.append(nombreEquipo)\r\n\r\n entrada.close()\r\n\r\n return equipos\r\n\r\n'''Corregir'''\r\n#5. Mostrar equipo con menor diferencia de goles\r\ndef mostrarEquipoMenorDiferenciaGoles(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n menorDiferencia = 1000\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n\r\n for linea in entrada:\r\n datos= linea.split(\"&\")\r\n nombreEquipo = datos[0]\r\n diferencia = int(datos[7])\r\n if diferencia < 0:\r\n diferencia = diferencia * -1 #Cambiamos el valor a positivo, haciendo más sencilla la comparación\r\n\r\n if diferencia < menorDiferencia :\r\n menorDiferencia = diferencia\r\n equipo = nombreEquipo\r\n\r\n entrada.close()\r\n\r\n return equipo\r\n\r\n'Incompleto'\r\n#6. Genera un nuevo documento\r\ndef generarArchivoNuevo(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n salida = open(\"Puntos.txt\" ,\"w\")\r\n\r\n listaEquipos = []\r\n listaUltimos = []\r\n\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n\r\n for linea in entrada:\r\n datos = linea.split(\"&\")\r\n nombreEquipo = datos[0]\r\n puntos = int(datos[8])\r\n listaEquipos.append((nombreEquipo, puntos))\r\n\r\n for valor in listaEquipos:\r\n menor = min(listaEquipos)\r\n if len(listaUltimos) < 5:\r\n listaUltimos.append(menor)\r\n listaEquipos.remove(menor)\r\n\r\n print(listaUltimos)\r\n\r\n\r\n\r\n listaUltimos.append(min(listaEquipos))\r\n\r\n\r\n entrada.close()\r\n salida.close()\r\n\r\n#7. crea una gráfica de los equipos vs puntos\r\ndef graficarPuntos(nombreArchivo):\r\n entrada = open(nombreArchivo, \"r\", encoding=\"UTF-8\")\r\n\r\n entrada.readline() # Título 1\r\n entrada.readline() # Título 2\r\n\r\n listaEquipos = []\r\n listaPuntos = []\r\n\r\n for linea in entrada:\r\n datos = linea.split(\"&\")\r\n listaEquipos.append(datos[0])\r\n listaPuntos.append(int(datos[8]))\r\n\r\n plot.plot(listaEquipos,listaPuntos)\r\n plot.show()\r\n\r\n\r\ndef main():\r\n #1.\r\n nombres = ordenarNombresAlfabeticamente(\"LigaMX.txt\")\r\n print(nombres)\r\n\r\n #2.\r\n lista = crearRelacionNombresYPuntos(\"LigaMX.txt\")\r\n print(lista)\r\n\r\n #3.\r\n listaEquipos = mostrarEquipos_MenosPartidosPerdidos(\"LigaMX.txt\")\r\n print(listaEquipos)\r\n\r\n #4.\r\n errores = buscarEquiposError(\"LigaMX.txt\")\r\n print(errores)\r\n\r\n #5.\r\n diferencia = mostrarEquipoMenorDiferenciaGoles(\"LigaMX.txt\")\r\n print(diferencia)\r\n\r\n\r\n #6.\r\n archivo = generarArchivoNuevo(\"LigaMX.txt\")\r\n\r\n\r\n #7.\r\n graficarPuntos(\"LigaMX.txt\")\r\n\r\nmain()","sub_path":"Mision_10.py","file_name":"Mision_10.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"311852504","text":"class FileAdapter():\n def __init__(self, filename):\n self.filename = filename\n\n def readFastaWithLabels(self):\n labels = []\n genome = ''\n\n with open(self.filename, 'r') as file:\n for l in file:\n if l[0] == '>':\n labels.append(l.rstrip())\n continue\n genome += l.rstrip()\n return labels, genome\n\n def readFasta(self):\n _, genome = self.readFastaWithLabels()\n return genome\n\n def readFastQSec(self, includeTag=False):\n with open(self.filename, 'r') as file:\n while True:\n tag = file.readline()\n\n if len(tag) == 0:\n break\n\n tag = tag.rstrip()\n sequence = file.readline().rstrip()\n file.readline()\n qual = file.readline().rstrip()\n\n if includeTag:\n yield tag, sequence, qual\n else:\n yield sequence, qual\n","sub_path":"core/adapters/fileadapter.py","file_name":"fileadapter.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"642180184","text":"#!/usr/bin/python\n\"\"\"task3.7\"\"\"\n# pylint: disable=C0103\n\n\ndef get_indexes(lst, number):\n \"\"\"\n return list of indexes\n searched number in lst, or None if number not in lst\n \"\"\"\n res = [ind for ind, num in enumerate(lst) if num == number]\n if res:\n return ' '.join(map(str, res))\n\nif __name__ == '__main__':\n in_lst = list(map(int, input().split()))\n fnum = int(input())\n print(get_indexes(in_lst, fnum))\n","sub_path":"task37.py","file_name":"task37.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"341847156","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\na=[]\r\nfor i in range(2,100):\r\n flag = 0\r\n for j in range(2,i//2+1):\r\n if(i%j==0):\r\n flag = 1\r\n break\r\n if flag == 0:\r\n a.append(i)\r\n \r\na.reverse()\r\n\r\n#print(a)\r\n\r\nS__A = []\r\nS__B = []\r\n\r\nA , B = 0, 0\r\n\r\nfor i in range(len(a)):\r\n if(A > B):\r\n S__B.append(a[i])\r\n B += a[i]\r\n #print(S__B)\r\n else:\r\n S__A.append(a[i])\r\n A += a[i]\r\n #print(S__A)\r\n \r\nS__A.reverse()\r\nS__B.reverse()\r\n\r\nprint('A =', A)\r\nprint('B =', B) \r\nprint('Sa =', S__A)\r\nprint('Sb =', S__B)\r\nprint('差の絶対値 =', abs(A - B))\r\n","sub_path":"0527/2210104049/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"348373380","text":"\"\"\"\nMain module that builds the JSON that needs to be submitted\nto the pipeline executor\n\"\"\"\nimport logging\nimport os\nimport sys\nimport json\nfrom runner.models import Port, Run\nfrom runner.run.processors.file_processor import FileProcessor\nfrom file_system.repository.file_repository import FileRepository\nfrom notifier.helper import generate_sample_data_content\nfrom .bin.oncotree_data_handler.OncotreeDataHandler import OncotreeDataHandler\nfrom django.db.models import Q\nfrom django.conf import settings\n\nWORKDIR = os.path.dirname(os.path.abspath(__file__))\nLOGGER = logging.getLogger(__name__)\n\n\ndef load_references():\n \"\"\"\n Loads reference data from the resources JSON\n \"\"\"\n data = json.load(open(os.path.join(WORKDIR, \"reference_jsons/helix_filters_resources.json\"), \"rb\"))\n return data\n\n\ndef get_baits_and_targets(assay, helix_filters_resources):\n \"\"\"\n From value in assay, retrieve target files from helix_filters_resources\n \"\"\"\n targets = helix_filters_resources[\"targets\"]\n\n target_assay = assay\n\n if assay.find(\"HemePACT_v4\") > -1:\n target_assay = \"HemePACT_v4_BAITS\"\n\n if assay.find(\"IMPACT505\") > -1:\n target_assay = \"IMPACT505_b37\"\n if assay.find(\"IMPACT410\") > -1:\n target_assay = \"IMPACT410_b37\"\n if assay.find(\"IMPACT468\") > -1:\n target_assay = \"IMPACT468_b37\"\n if assay.find(\"IMPACT341\") > -1:\n target_assay = \"IMPACT341_b37\"\n if assay.find(\"IDT_Exome_v1_FP\") > -1:\n target_assay = \"IDT_Exome_v1_FP_b37\"\n if assay.find(\"IMPACT468+08390\") > -1:\n target_assay = \"IMPACT468_08390\"\n if assay.find(\"IMPACT468+Poirier_RB1_intron_V2\") > -1:\n target_assay = \"IMPACT468_08050\"\n\n if target_assay in targets:\n return {\"class\": \"File\", \"location\": str(targets[target_assay][\"targets_list\"])}\n else:\n error_msg = \"ERROR: Targets for Assay not found in helix_filters_resources.json: %s\" % assay\n LOGGER.error(error_msg)\n\n\ndef create_cwl_file_obj(file_path):\n \"\"\"\n Given a filepath, return a dictionary with class File and JUNO-specific URI\n \"\"\"\n cwl_file_obj = {\"class\": \"File\", \"location\": \"juno://%s\" % file_path}\n return cwl_file_obj\n\n\ndef get_file_obj(file_obj):\n \"\"\"\n Given file_obj, construct a dictionary of class File, that file's\n JUNO-specific URI file path, and a list of secondary files with\n JUNO-specific URI file paths\n \"\"\"\n secondary_file_list = []\n file_location = file_obj[\"location\"].replace(\"file://\", \"\")\n if \"secondaryFiles\" in file_obj:\n for single_secondary_file in file_obj[\"secondaryFiles\"]:\n secondary_file_location = single_secondary_file[\"location\"].replace(\"file://\", \"\")\n secondary_file_cwl_obj = create_cwl_file_obj(secondary_file_location)\n secondary_file_list.append(secondary_file_cwl_obj)\n file_cwl_obj = create_cwl_file_obj(file_location)\n if secondary_file_list:\n file_cwl_obj[\"secondaryFiles\"] = secondary_file_list\n return file_cwl_obj\n\n\ndef get_files_from_port(port_obj):\n file_list = []\n if isinstance(port_obj, list):\n for single_file in port_obj:\n if isinstance(single_file, list):\n file_list.append(get_files_from_port(single_file))\n else:\n file_list.append(get_file_obj(single_file))\n elif isinstance(port_obj, dict):\n file_list.append(get_file_obj(port_obj))\n return file_list\n\n\ndef list_keys_for_filters():\n \"\"\"\n Returns a list of keys expected in the JSON to be submitted to the pipeline; these\n keys will have a list of values in the JSON\n \"\"\"\n keys = [\n \"mutation_maf_files\",\n \"mutation_svs_maf_files\",\n \"mutation_svs_txt_files\",\n \"targets_list\",\n \"tumor_bam_files\",\n \"normal_bam_files\",\n ]\n return set(keys)\n\n\ndef single_keys_for_filters():\n \"\"\"\n Returns a list of keys expected in the JSON to be submitted to the pipeline; these\n keys will have a single of values in the JSON\n \"\"\"\n keys = [\n \"assay\",\n \"project_prefix\",\n \"is_impact\",\n \"analyst_file\",\n \"portal_file\",\n \"portal_CNA_file\",\n \"analysis_gene_cna_file\",\n ]\n return set(keys)\n\n\ndef construct_helix_filters_input(argos_run_id_list, dmp_samples=None):\n \"\"\"\n Main function. From a list of run IDs, build a JSON that combines\n the runs data into one JSON expected by the helix filters pipeline\n \"\"\"\n input_json = {}\n pairs = []\n list_keys = list_keys_for_filters()\n single_keys = single_keys_for_filters()\n\n for key in list_keys:\n input_json[key] = list()\n\n for single_run_id in argos_run_id_list:\n port_list = Port.objects.filter(run=single_run_id)\n pair_info = {}\n for single_port in port_list:\n name = single_port.name\n value = single_port.value\n if name == \"maf\":\n input_json[\"mutation_maf_files\"].append(get_file_obj(value))\n pair_info[\"pair_maf\"] = get_file_obj(value)\n if name == \"snp_pileup\":\n pair_info[\"snp_pileup\"] = get_file_obj(value)\n if name == \"pair\":\n normal_id = value[1][\"ID\"]\n tumor_id = value[0][\"ID\"]\n pair_info[\"normal_id\"] = normal_id\n pair_info[\"tumor_id\"] = tumor_id\n pair_info[\"pair_id\"] = \"{}.{}\".format(tumor_id, normal_id)\n if name == \"maf_file\":\n input_json[\"mutation_svs_maf_files\"].append(get_file_obj(value))\n if name == \"portal_file\":\n input_json[\"mutation_svs_txt_files\"].append(get_file_obj(value))\n if name == \"project_prefix\":\n input_json[name] = single_port.value\n if name == \"assay\":\n if \"impact\" in single_port.value.lower():\n input_json[\"is_impact\"] = True\n else:\n input_json[\"is_impact\"] = False\n input_json[\"assay\"] = single_port.value\n if name == \"tumor_bam\":\n input_json[\"tumor_bam_files\"].append(get_file_obj(value))\n if name == \"normal_bam\":\n input_json[\"normal_bam_files\"].append(get_file_obj(value))\n pairs.append(pair_info)\n\n references = convert_references(input_json[\"assay\"])\n input_json.update(references)\n\n # some default values\n project_prefix = input_json[\"project_prefix\"]\n input_json[\"project_id\"] = project_prefix\n input_json[\"project_short_name\"] = project_prefix\n input_json[\"project_name\"] = project_prefix\n input_json[\"project_description\"] = project_prefix\n input_json[\"cancer_study_identifier\"] = project_prefix\n\n # Gotta retrieve extra info that's not in the run porto have to query the database\n #\n # Get oncotree codes from samples in project_prefix/request_id FileMetadata\n # will need to change project_prefix to request_id values everywhere, but for now we assume\n # there is only one project_prefix/request_id per helix_filters run\n input_json[\"cancer_type\"] = get_oncotree_codes(project_prefix)\n input_json[\"argos_version_string\"] = get_argos_pipeline_version(argos_run_id_list)\n input_json[\"project_pi\"] = get_project_pi(argos_run_id_list)\n input_json[\"request_pi\"] = get_request_pi(argos_run_id_list)\n\n # facets input\n input_json[\"pairs\"] = pairs\n\n # generate data_clinical file\n input_json[\"data_clinical_file\"] = create_data_clinical_file(argos_run_id_list, dmp_samples)\n\n # need this for aion\n input_json[\"lab_head_email\"] = get_lab_head_email(argos_run_id_list)\n\n return input_json\n\n\ndef create_data_clinical_file(run_id_list, dmp_samples):\n files = list()\n pipeline_names = set()\n pipeline_githubs = set()\n pipeline_versions = set()\n for run_id in run_id_list:\n argos_run = Run.objects.get(id=run_id)\n pipeline = argos_run.app\n pipeline_names.add(pipeline.name)\n pipeline_githubs.add(pipeline.github)\n pipeline_versions.add(pipeline.version)\n files = files + get_files_from_run(argos_run)\n data_clinical_content = generate_sample_data_content(\n files,\n pipeline_name=\",\".join(pipeline_names),\n pipeline_github=\",\".join(pipeline_githubs),\n pipeline_version=\",\".join(pipeline_versions),\n dmp_samples=dmp_samples,\n )\n data_clinical_content = data_clinical_content.strip()\n return {\"class\": \"File\", \"basename\": \"sample_data_clinical.txt\", \"contents\": data_clinical_content}\n\n\ndef get_files_from_run(r):\n files = list()\n inp_port = Port.objects.filter(run_id=r.id, name=\"pair\").first()\n for p in inp_port.db_value[0][\"R1\"]:\n files.append(FileProcessor.get_file_path(p[\"location\"]))\n for p in inp_port.db_value[0][\"R2\"]:\n files.append(FileProcessor.get_file_path(p[\"location\"]))\n for p in inp_port.db_value[0][\"zR1\"]:\n files.append(FileProcessor.get_file_path(p[\"location\"]))\n for p in inp_port.db_value[0][\"zR2\"]:\n files.append(FileProcessor.get_file_path(p[\"location\"]))\n for p in inp_port.db_value[0][\"bam\"]:\n files.append(FileProcessor.get_file_path(p[\"location\"]))\n return files\n\n\ndef build_request_ids_query(data):\n \"\"\"\n Build complex Q object run id query from given data\n\n Only does OR queries, as seen in line\n\n query |= item\n\n \"\"\"\n data_query_set = [Q((\"metadata__{}\".format(settings.REQUEST_ID_METADATA_KEY), value)) for value in set(data)]\n query = data_query_set.pop()\n for item in data_query_set:\n query |= item\n return query\n\n\ndef get_project_pi(run_id_list):\n project_pis = set()\n for run_id in run_id_list:\n argos_run = Run.objects.get(id=run_id)\n project_pi = format_msk_id(argos_run.tags[\"labHeadEmail\"])\n project_pis.add(project_pi)\n return \",\".join(list(sorted(project_pis)))\n\n\ndef get_lab_head_email(run_id_list):\n lab_head_emails = set()\n for run_id in run_id_list:\n argos_run = Run.objects.get(id=run_id)\n lab_head_email = argos_run.tags[\"labHeadEmail\"]\n lab_head_emails.add(lab_head_email)\n return \",\".join(list(sorted(lab_head_emails)))\n\n\ndef get_request_pi(run_id_list):\n request_pis = set()\n files = FileRepository.all()\n all_request_ids = set()\n # reducing number of queries\n for run_id in run_id_list:\n argos_run = Run.objects.get(id=run_id)\n run_request_id = argos_run.tags[settings.REQUEST_ID_METADATA_KEY]\n all_request_ids.add(run_request_id)\n for request_id in all_request_ids:\n investigator_emails = FileRepository.filter(\n queryset=files, metadata={settings.REQUEST_ID_METADATA_KEY: request_id}\n ).values_list(\"metadata__investigatorEmail\", flat=True)\n request_pis = request_pis.union(set(investigator_emails))\n request_pis_final = list()\n for request_pi in request_pis:\n if request_pi:\n request_pis_final.append(format_msk_id(request_pi))\n return \",\".join(request_pis_final)\n\n\ndef get_argos_pipeline_version(run_id_list):\n versions = set()\n for run_id in run_id_list:\n argos_run = Run.objects.get(id=run_id)\n versions.add(argos_run.app.version)\n return \"_\".join(list(sorted(versions)))\n\n\ndef format_msk_id(email_address):\n return email_address.split(\"@\")[0]\n\n\ndef convert_references(assay):\n \"\"\"\n Return a dictionary of references based on \"assay\" for targets_list\n \"\"\"\n helix_filters_resources = load_references()\n references = dict()\n targets_list = get_baits_and_targets(assay, helix_filters_resources)\n references[\"assay_coverage\"] = str(get_assay_coverage(assay, helix_filters_resources))\n references[\"targets_list\"] = targets_list\n references[\"known_fusions_file\"] = {\"class\": \"File\", \"location\": str(helix_filters_resources[\"known_fusions_file\"])}\n references[\"IMPACT_gene_list\"] = {\"class\": \"File\", \"location\": str(helix_filters_resources[\"IMPACT_gene_list\"])}\n references[\"microsatellites_file\"] = {\n \"class\": \"File\",\n \"location\": str(helix_filters_resources[\"microsatellites_file\"]),\n }\n return references\n\n\ndef get_assay_coverage(assay, helix_filters_resources):\n assay_coverages_list = helix_filters_resources[\"assay_tmb_coverage_values\"]\n assay_coverage = 0\n for key in assay_coverages_list.keys():\n curr_assay = key.lower()\n if curr_assay in assay.lower():\n assay_coverage = assay_coverages_list[key]\n return assay_coverage\n\n\ndef get_oncotree_codes(request_id):\n oncotree_dh = OncotreeDataHandler()\n files = FileRepository.all()\n oncotree_codes_tmp = set(\n FileRepository.filter(queryset=files, metadata={settings.REQUEST_ID_METADATA_KEY: request_id}).values_list(\n \"metadata__{}\".format(settings.ONCOTREE_METADATA_KEY), flat=True\n )\n )\n oncotree_codes = list()\n for val in oncotree_codes_tmp:\n if val:\n oncotree_codes.append(val)\n if not oncotree_codes: # hack; if there are no oncotree codes, just say it's mixed\n return \"mixed\"\n shared_nodes = oncotree_dh.find_shared_nodes_by_code_list(oncotree_codes)\n common_anc = oncotree_dh.get_highest_level_shared_node(shared_nodes)\n if common_anc.code.lower() == \"tissue\":\n common_anc.code = \"mixed\"\n return common_anc.code.lower()\n\n\nif __name__ == \"__main__\":\n RUN_ID_LIST = []\n for single_arg in sys.argv[1:]:\n RUN_ID_LIST.append(single_arg)\n INPUT_JSON = construct_helix_filters_input(RUN_ID_LIST)\n","sub_path":"runner/operator/helix_filters/dev/construct_helix_filters_input.py","file_name":"construct_helix_filters_input.py","file_ext":"py","file_size_in_byte":13547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"176535465","text":"# https://www.acmicpc.net/problem/2805\n# 나무 자르기\n\nfrom sys import stdin\ninput = stdin.readline\n\ndef chop(nums, h):\n return sum([x - h for x in nums if x > h])\n\nnum, limit = map(int, input().split())\nnums = list(map(int, input().split()))\n\nstart = 0\nend = max(nums)\nans = None\n\nwhile start <= end:\n mid = (start + end) // 2\n result = chop(nums, mid)\n\n if result >= limit:\n start = mid + 1\n ans = mid\n else:\n end = mid - 1\n\nprint(ans)\n","sub_path":"SeonjaeHyeon/code_3week/02_2805.py","file_name":"02_2805.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"172932105","text":"\"\"\"test_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path, include \n\nfrom . import views\n\napp_name = \"homepage\"\n\nurlpatterns = [\n\tpath(\"\",views.homepage, name=\"homepage\"), # Path to the url create account\n\tpath(\"addToCart/?=id\", views.add_to_cart,name=\"add_to_cart\"), # pos argument\n\tpath(\"orders/\", views.order_page, name=\"orders\"),\n path(\"search/\",views.search_page, name=\"search\"),\n path(\"query\", views.search, name=\"search_query\"),\n path(\"submitOrder/\", views.submit_order, name=\"submit_order\"),\n path(\"remove_from_cart/?=id\", views.remove_from_cart, name=\"remove_from_cart\"),\n path(\"cart\", views.cart, name=\"cart\"),\n path(\"retrieveOrder/\", views.retrieve_order, name=\"retrieve_order\"),\n]\n","sub_path":"homepage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"13019823","text":"from bs4 import BeautifulSoup\r\nimport requests\r\n\r\n# add try block for wrong parser error \"UnicodeEncodeError\", loop and try all parsers\r\n\r\nclass Website:\r\n\r\n def __init__(self, name, url, tag_name, class_name, **kwargs):\r\n self.name = name\r\n self.url = url\r\n self.tag_name = tag_name\r\n self.class_name = class_name\r\n self.retrieval_tags = kwargs\r\n self.soup = self.get_soup()\r\n self.article_source = self.get_article_source()\r\n self.tag_dict = self.build_tag_dict()\r\n self.clean_article_links()\r\n self.title_link_match = self.get_title_link_match()\r\n\r\n def get_soup(self):\r\n \"\"\"Returns html from given url\"\"\"\r\n try:\r\n source = requests.get(self.url).text\r\n soup = BeautifulSoup(source, 'lxml')\r\n return soup\r\n except (requests.exceptions.ConnectionError) as e:\r\n print('Something may be wrong with the websites URL')\r\n print('No connection was established')\r\n\r\n def show_soup(self):\r\n \"\"\"Prints indented hmtl from url source gievn\"\"\"\r\n print(self.soup.prettify())\r\n\r\n def get_article_source(self):\r\n \"\"\"gets source html with given tags during instatiation\"\"\"\r\n article_source = self.soup.find_all(self.tag_name, class_=self.class_name)\r\n return article_source\r\n\r\n # add try block here\r\n def get_article_info(self, article_peice):\r\n \"\"\"Drills down to title info in html code given tags during class instatiation\"\"\"\r\n retrieved_info = []\r\n for source in self.article_source:\r\n walk_list = [source]\r\n for tag in self.retrieval_tags[article_peice]:\r\n if tag[1] == 'attribute':\r\n attribute = getattr(walk_list[-1], tag[0])\r\n walk_list.append(attribute)\r\n elif tag[1] == 'element':\r\n element = tag[0]\r\n walk_list.append(walk_list[-1][element])\r\n\r\n retrieved_info.append(walk_list[-1])\r\n return retrieved_info\r\n\r\n def build_tag_dict(self):\r\n \"\"\"Builds class dict from tags given during instantiation\"\"\"\r\n tag_dict = {}\r\n for tag in self.retrieval_tags:\r\n tag_dict[tag] = self.get_article_info(tag)\r\n return tag_dict\r\n\r\n def clean_article_links(self):\r\n \"\"\"Add url to links that dont include full url to article *BROKEN\"\"\"\r\n if 'link' in self.tag_dict:\r\n for link in self.tag_dict['link']:\r\n link_index = self.tag_dict['link'].index(link)\r\n if self.url not in link:\r\n self.tag_dict['link'][link_index] = self.url + link\r\n\r\n def get_title_link_match(self):\r\n \"\"\"Return tuples with title and matching link\"\"\"\r\n try:\r\n readable_zip = zip(self.tag_dict['title'], self.tag_dict['link'])\r\n readable_info = [tup for tup in readable_zip]\r\n return readable_info\r\n except NameError:\r\n print(\"Either 'title' or 'link' do not exist for this class\")\r\n\r\n# EXAMPLE OF WEBSITE CLASS INSTANCES\r\n# wired = Website('wired', 'http://www.wired.com', 'li', 'post-listing-list-item__post',\r\n# title=(('h5', 'attribute'), ('text', 'attribute')), link=(('a', 'attribute'), ('href', 'element')))\r\n#\r\n# geekwire = Website('geekwire', 'http://www.geekwire.com', 'h2', 'entry-title',\r\n# title=(('a', 'attribute', ), ('text', 'attribute')), link=(('a', 'attribute'), ('href', 'element')))\r\n#\r\n","sub_path":"ArticleSoup.py","file_name":"ArticleSoup.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"517619429","text":"from scheme import Json\n\nfrom spire.wsgi.util import Mount\n\nclass ServiceEndpoint(Mount):\n def __init__(self, runtime, service):\n super(ServiceEndpoint, self).__init__()\n self.runtime = runtime\n self.service = service\n\n def _dispatch_request(self, request, response):\n service = self.service\n if request.method == 'GET':\n return self._prepare_response(response,\n {'id': service['id'], 'pid': self.runtime.pid})\n\n data = Json.unserialize(request.data)\n if data['status'] == 'restarting':\n self._prepare_response(response, {'status': 'restarting'})\n self.runtime.reload()\n elif data['status'] == 'starting':\n content = self.runtime._execute_service_startup(self.service['id'], data.get('stage'))\n self._prepare_response(response, content)\n\n def _prepare_response(self, response, content):\n response.mimetype = 'application/json'\n response.data = Json.serialize(content)\n","sub_path":"spire/runtime/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99532884","text":"# Write a method that takes a string and returns true if it is a\n# palindrome. A palindrome is a string that is the same whether written\n# backward or forward. Assume that there are no spaces; only lowercase\n# letters will be given.\n#\n# Difficulty: easy.\n\ndef palindrome(string):\n for i in range(len(string) // 2):\n if string[i] != string[len(string) - 1 - i]:\n return False\n return True\n\nprint(palindrome(\"abc\") == False)\nprint(palindrome(\"abcba\") == True)\nprint(palindrome(\"z\") == True)","sub_path":"Practice 1/Problems/07 - Palindrome (E).py","file_name":"07 - Palindrome (E).py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"637460576","text":"'''\nCreated on 18-Apr-2016\n\n@author: Asawari.Vaidya\n'''\nimport inspect\n\nfrom PythonPaysafeSDK import ThreeDSecure\nfrom PythonPaysafeSDK import common\n\n\nclass ThreeDSecureService(object):\n '''\n classdocs\n '''\n # Define URL paths for Purchase \n _MONITOR_PATH = '/threedsecure/monitor'\n _URI = '/threedsecure/v1'\n _ENROLLMENT_PATH = '/enrollmentchecks'\n _URI_SEPARATOR = '/'\n _AUTHENTICATIONS_PATH = '/authentications'\n _ACCOUNTS=\"/accounts/\"\n \n def __init__(self, optimal_object):\n '''\n Constructor\n '''\n self.optimal_object = optimal_object\n self._account_no = optimal_object._account_number\n \n '''\n Prepare URL for process request\n @param: Chunks of paths\n @return: Complete URL for Processing Request\n '''\n def _prepare_uri(self, path):\n return self._URI + path \n \n '''\n Process the response from the Server\n @param: response object, class name\n @return: object of class\n '''\n def _process_response(self, response, class_name):\n if isinstance(response, int):\n response_status = class_name(None)\n response_status.status = response\n return (response_status)\n elif response is None:\n return class_name(None)\n elif isinstance(response, common.Error.Error):\n return self.prepare_error(class_name, response.code, \n response.message)\n else:\n return (class_name(response))\n \n '''\n Prepare Error Response\n @param: response object, class name\n @return: object of class\n ''' \n def prepare_error(self, class_name, error_code, error_message):\n error_object_response = class_name(None)\n error_obj = common.Error.Error(None)\n error_obj.code(error_code)\n error_obj.message(error_message)\n error_object_response.error(error_obj.__dict__)\n return (error_object_response)\n\n '''\n Monitor\n \n @param: None\n @return: Response Status\n @raise: IOException\n @raise: OptimalException\n '''\n def monitor(self):\n FULL_URL = self._MONITOR_PATH\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"GET\",\n url=FULL_URL,\n data=None) \n return (self._process_response(response, ThreeDSecure.EnrollmentChecks.EnrollmentChecks))\n \n '''\n Submit Enrollment Request\n @param: EnrollmentChecks Object\n @return: EnrollmentChecks Object\n @raise: IOException\n @raise: OptimalException\n '''\n def submit_purchase_enrollment(self, data):\n FULL_URL = self._prepare_uri(self._ACCOUNTS + \\\n self._account_no + \\\n self._ENROLLMENT_PATH +\\\n self._URI_SEPARATOR)\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"POST\",\n url=FULL_URL,\n data=data) \n return (self._process_response(response, ThreeDSecure.EnrollmentChecks.EnrollmentChecks))\n \n '''\n Lookup Enrollment by Id\n @return: EnrollmentChecks object\n @raise exception: IOException\n @raise exception: OptimalException\n '''\n def lookup_enrollment(self, data):\n enrollment_id = data.id\n if inspect.ismethod(enrollment_id):\n err_msg = \"EnrollmentChecks Id not available\"\n return (self.prepare_error(\n ThreeDSecure.EnrollmentChecks.EnrollmentChecks, \n \"400\", \n err_msg))\n del data.id\n \n FULL_URL = self._prepare_uri(self._ACCOUNTS + \\\n self._account_no + \\\n self._ENROLLMENT_PATH +\\\n self._URI_SEPARATOR +\\\n enrollment_id)\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"GET\", \n url=FULL_URL, \n data=None) \n return (self._process_response(response, ThreeDSecure.EnrollmentChecks.EnrollmentChecks))\n\n '''\n Submit Authentications Request\n @param: Authentications Object\n @return: Authentications Object\n @raise: IOException\n @raise: OptimalException\n '''\n def submit_purchase_authentications(self, data):\n enrollment_id = data.enrollmentchecks.id\n if inspect.ismethod(enrollment_id):\n err_msg = \"EnrollmentChecks Id not available\"\n return (self.prepare_error(\n ThreeDSecure.Authentications.Authentications, \n \"400\", \n err_msg))\n del data.enrollmentchecks\n \n FULL_URL = self._prepare_uri(self._ACCOUNTS + \\\n self._account_no + \\\n self._ENROLLMENT_PATH + \\\n\t\t\t\t\t\t\t\t\t self._URI_SEPARATOR + \\\n enrollment_id + \\\n self._AUTHENTICATIONS_PATH)\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"POST\",\n url=FULL_URL,\n data=data) \n return (self._process_response(response, ThreeDSecure.Authentications.Authentications)) \n\n '''\n Lookup Authentications by Id\n @return: Authentications object\n @raise exception: IOException\n @raise exception: OptimalException\n '''\n def lookup_authentications(self, data): \n authentication_id = data.id\n if inspect.ismethod(authentication_id):\n err_msg = \"Authentications Id not available\"\n return (self.prepare_error(\n ThreeDSecure.Authentications.Authentications, \n \"400\", \n err_msg))\n del data.id\n \n FULL_URL = self._prepare_uri(self._ACCOUNTS + \\\n self._account_no + \\\n self._AUTHENTICATIONS_PATH + \\\n self._URI_SEPARATOR + \\\n authentication_id)\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"GET\", \n url=FULL_URL, \n data=None) \n return (self._process_response(response, ThreeDSecure.Authentications.Authentications)) \n \n '''\n Lookup Authentications and corresponsing Enrollment Check\n @return: Authentications object\n @raise exception: IOException\n @raise exception: OptimalException\n '''\n def lookup_authentications_and_enrollment(self, data):\n _subcomponent_enrollment = '?fields=enrollmentchecks'\n \n authentication_id = data.id\n if inspect.ismethod(authentication_id):\n err_msg = \"Authentications Id not available\"\n return (self.prepare_error(\n ThreeDSecure.Authentications.Authentications, \n \"400\", \n err_msg))\n del data.id\n \n FULL_URL = self._prepare_uri(self._ACCOUNTS + \\\n self._account_no + \\\n self._AUTHENTICATIONS_PATH + \\\n self._URI_SEPARATOR + \\\n authentication_id + \\\n _subcomponent_enrollment)\n # print (\"Communicating to \", FULL_URL)\n response = self.optimal_object.process_request(\n req_method=\"GET\", \n url=FULL_URL, \n data=None) \n return (self._process_response(response, ThreeDSecure.Authentications.Authentications)) \n","sub_path":"src/PythonPaysafeSDK/ThreeDSecure/ThreeDSecureService.py","file_name":"ThreeDSecureService.py","file_ext":"py","file_size_in_byte":8896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"467294456","text":"#!/usr/bin/env python\nimport pymongo\n\n# establish a connection to the database\nconnection = pymongo.MongoClient(\"mongodb://mongo.loc\")\n\n# get a handle to the school database\ndb = connection.video\nmovieDetails = db.movieDetails\n\n\nquery = {\n}\n\ntry:\n doc = movieDetails.find(query)\n\nexcept Exception as e:\n print(\"Unexpected error:\", type(e), e)\n\n# 6\nprint(doc.count())\n\n","sub_path":"chapter2/hw2-5.py","file_name":"hw2-5.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"441069242","text":"import matplotlib.pyplot as plt\nimport xlrd\nimport os\n\n\ndef create_worksheet(table, sheet):\n # возвращает рабочий лист из Excel файла с именем Table\n # и страницы sheet\n workbook = xlrd.open_workbook(table)\n worksheet = workbook.sheet_by_name(sheet)\n return worksheet\n\n\ndef table_data(worksheet, Axx):\n # Функция, возвращающая значения для новых осей\n x = []\n y = []\n for i in range(0,worksheet.nrows):\n x.append(worksheet.cell(i,0).value)\n y.append(abs(worksheet.cell(i,1).value)) # здесь берем модуль\n if Axx == 1:\n return x\n else:\n return y\n\n\ndef graphic_my(x, y):\n # функция построения графика по массиву x-ов и y-ов\n fig, ax = plt.subplots()\n ax.plot(x, y)\n ax.set(xlabel='Time', ylabel='Amplitude')\n plt.show()\n\n\ndef maxes_of_list_y(y):\n # функция получения массива индексов локальных максимумов\n indexes = []\n y_out = []\n for i in range(1,len(y)-1):\n if (y[i] > y[i+1]) & (y[i] > y[i-1]):\n indexes.append(i)\n y_out.append(y[i])\n return [y_out, indexes]\n\n\ndef reduce_array(indexes, arr):\n # возвращает массив, элементов с индексами indexes из массива arr\n j = 0\n final_arr = []\n for i in indexes:\n final_arr.append(arr[i])\n return final_arr\n\n\ndef reduce_loop(amount, x, y):\n # функция, убирающая amount раз элементы около локальных максимумов\n # возвращает матрицу, один столбец - х, а другой - у\n for i in range(amount):\n temp = maxes_of_list_y(y)\n ind = temp[1]\n x = reduce_array(ind, x)\n y = reduce_array(ind, y)\n # print(len(y))\n return [x, y]\n\n\ndef some_rezonanses(amount, y, x):\n # функция возвращает матрицу с amount максимумами: координаты y,x и индексами\n temp = maxes_of_list_y(y)\n maximums = sorted(temp[0], reverse=True)\n # print(maximums)\n maxes = []\n indexes = []\n xes = []\n for i in range(amount):\n maxes.append(maximums[i])\n # print(maxes)\n indexes.append(y.index(maximums[i]))\n # print(indexes)\n xes.append(x[indexes[i]])\n return [maxes, xes, indexes]\n\n\ndef line_2_dots(x1, y1, x2, y2):\n # коэффициенты прямой по двум точкам\n k = (y1 - y2) / (x1 - x2)\n b = y2 - k * x2\n return [k, b]\n\n\ndef peak_picking_method(index_max, y, x):\n # Реализация метода половинной мощности\n # Делается так: от пика спускаемся в каждую сторону до тех пор,\n # пока у[i] не будет меньше заданного значения, а потом линейной\n # интерполяцией находится значение частоты для левой частоты\n i = index_max\n # print(y[index_max]/(2**(1/2)))\n while y[i] > y[index_max]/(2**(1/2)):\n i -= 1\n temp = line_2_dots(x[i],y[i],x[i+1],y[i+1])\n x_left = ( y[index_max]/(2**(1/2)) - temp[1] ) / temp[0]\n # print(x_left)\n\n # то же самое, но для правой точки\n i = index_max\n while y[i] > y[index_max] / (2 ** (1 / 2)):\n i += 1\n temp = line_2_dots(x[i], y[i], x[i - 1], y[i - 1])\n x_right = ( y[index_max]/(2**(1/2)) - temp[1] ) / temp[0]\n # print(x_right)\n\n delta_w = x_right - x_left\n return delta_w/(2*x[index_max])\n\n\n# print(os.listdir()) # нужно, чтобы правильно ввести название excel-файла\n\n# получение листа из таблицы\nworksheet = create_worksheet('Signal_Table.xls', 'Sheet_1')\n\n# Вытаскиваниие из лист координат х и у точек\nx = table_data(worksheet, 1)\ny = table_data(worksheet, 2)\n\n# убирание точек вокруг локальных максимумов\n# в принципе, здесь надо делать сглаживание/аппроксимацию/интерполяцию\n# для входных данных, т.к. пик может получиться слишком тонким\na = (reduce_loop(5, x, y))\nx = a[0]\ny = a[1]\n\n# Получение матрицы с 5 локальными экстремумами, отсортированными по убыванию\nExtremums = some_rezonanses(4, y, x)\nprint(Extremums[0], \"\\n\", Extremums[1])\n\n# Применение метода половинной мощности\nfor i in range(4):\n print(\"Демфирование для \", i+1, \" резонанса \", peak_picking_method(Extremums[2][i], y, x))\n\n# Построение графика\ngraphic_my(x, y)\n\n\n","sub_path":"diplom/Signal_test_post.py","file_name":"Signal_test_post.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"398980755","text":"from djoser.serializers import TokenCreateSerializer as \\\n DjoserTokenCreateSerializer\nfrom rest_framework.validators import ValidationError\n\n\nclass TokenCreateSerializer(DjoserTokenCreateSerializer):\n\n def validate(self, attrs):\n email = attrs.get(\"email\")\n\n if isinstance(email, str):\n email = email.lower()\n\n return super().validate({\n **attrs,\n \"email\": email,\n })\n\n def create(self, validated_data):\n raise ValidationError(\"Create method disabled.\")\n\n def update(self, instance, validated_data):\n raise ValidationError(\"Update method disabled.\")\n","sub_path":"fix_the_news/api/auth/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"44928155","text":"# Time Complexity : O(V+E)\n# Space Complexity : O(V+E)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this :\n\n\n# Your code here along with comments explaining your approach\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n if len(prerequisites) == 0:\n return True\n \n inDeg = [0 for _ in range(numCourses)]\n hMap = {}\n cLeft = numCourses\n q = deque()\n \n for i in prerequisites:\n inDeg[i[0]] += 1\n if i[1] not in hMap.keys():\n hMap[i[1]] = [i[0]]\n else:\n hMap[i[1]].append(i[0])\n \n for i in inDeg:\n if i == 0:\n cLeft -= 1\n \n \n for i in range(numCourses):\n if inDeg[i] == 0:\n q.append(i)\n \n while len(q) != 0 and cLeft != 0:\n curr = q.popleft()\n if curr in hMap.keys():\n for i in hMap[curr]:\n inDeg[i] -= 1\n \n if inDeg[i] == 0:\n cLeft -= 1\n q.append(i)\n \n if cLeft == 0:\n return True\n else:\n return False","sub_path":"problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"192972685","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2022-2023 by SCICO Developers\n# All rights reserved. BSD 3-clause License.\n# This file is part of the SCICO package. Details of the copyright and\n# user license can be found in the 'LICENSE' file distributed with the\n# package.\n\n\"\"\"Support functions for manipulating Jupyter notebooks.\"\"\"\n\n\nimport re\nfrom timeit import default_timer as timer\n\nimport nbformat\nfrom nbconvert.preprocessors import CellExecutionError, ExecutePreprocessor\nfrom py2jn.tools import py_string_to_notebook, write_notebook\n\n\ndef py_file_to_string(src):\n \"\"\"Preprocess example script file and return result as a string.\"\"\"\n\n with open(src, \"r\") as srcfile:\n # Drop header comment\n for line in srcfile:\n if line[0] != \"#\":\n break # assume first non-comment line is a newline that can be dropped\n # Insert notebook plot config after last import\n lines = []\n import_seen = False\n for line in srcfile:\n line = re.sub('^r\"\"\"', '\"\"\"', line) # remove r from r\"\"\"\n line = re.sub(\":cite:`([^`]+)`\", r'', line) # fix cite format\n if import_seen:\n # Once an import statement has been seen, break on encountering a line that\n # is neither an import statement nor a newline, nor a component of an import\n # statement extended over multiple lines, nor an os.environ statement, nor\n # components of a try/except construction (note that handling of these final\n # two cases is probably not very robust).\n if not re.match(\n r\"(^import|^from|^\\n$|^\\W+[^\\W]|^\\)$|^os.environ|^try:$|^except)\", line\n ):\n lines.append(line)\n break\n else:\n # Set flag indicating that an import statement has been seen once one has\n # been encountered\n if re.match(\"^(import|from)\", line):\n import_seen = True\n lines.append(line)\n # Backtrack through list of lines to find last import statement\n n = 1\n for line in lines[-2::-1]:\n if re.match(\"^(import|from)\", line):\n break\n else:\n n += 1\n # Insert notebook plotting config directly after last import statement\n lines.insert(-n, \"plot.config_notebook_plotting()\\n\")\n\n # Process remainder of source file\n for line in srcfile:\n if re.match(\"^input\\(\", line): # end processing when input statement encountered\n break\n line = re.sub('^r\"\"\"', '\"\"\"', line) # remove r from r\"\"\"\n line = re.sub(\":cite:\\`([^`]+)\\`\", r'', line) # fix cite format\n lines.append(line)\n\n # Backtrack through list of lines to remove trailing newlines\n n = 0\n for line in lines[::-1]:\n if re.match(\"^\\n$\", line):\n n += 1\n else:\n break\n lines = lines[0:-n]\n\n return \"\".join(lines)\n\n\ndef script_to_notebook(src, dst):\n \"\"\"Convert a Python example script into a Jupyter notebook.\"\"\"\n\n s = py_file_to_string(src)\n nb = py_string_to_notebook(s)\n write_notebook(nb, dst)\n\n\ndef read_notebook(fname):\n \"\"\"Read a notebook from the specified notebook file.\"\"\"\n\n try:\n nb = nbformat.read(fname, as_version=4)\n except (AttributeError, nbformat.reader.NotJSONError):\n raise RuntimeError(\"Error reading notebook file %s.\" % fname)\n return nb\n\n\ndef execute_notebook(fname):\n \"\"\"Execute the specified notebook file.\"\"\"\n\n with open(fname) as f:\n nb = nbformat.read(f, as_version=4)\n ep = ExecutePreprocessor(timeout=None)\n try:\n t0 = timer()\n out = ep.preprocess(nb)\n t1 = timer()\n with open(fname, \"w\", encoding=\"utf-8\") as f:\n nbformat.write(nb, f)\n except CellExecutionError:\n print(f\"ERROR executing {fname}\")\n return False\n print(f\"{fname} done in {(t1 - t0):.1e} s\")\n return True\n\n\ndef notebook_executed(nbfn):\n \"\"\"Determine whether the notebook at `nbfn` has been executed.\"\"\"\n\n try:\n nb = nbformat.read(nbfn, as_version=4)\n except (AttributeError, nbformat.reader.NotJSONError):\n raise RuntimeError(\"Error reading notebook file %s.\" % pth)\n cells = nb[\"worksheets\"][0][\"cells\"]\n for n in range(len(nb[\"cells\"])):\n if cells[n].cell_type == \"code\" and cells[n].execution_count is None:\n return False\n return True\n\n\ndef same_notebook_code(nb1, nb2):\n \"\"\"Return ``True`` if the code cells of notebook objects `nb1` and `nb2`\n are all the same.\n \"\"\"\n\n if \"cells\" in nb1:\n nb1c = nb1[\"cells\"]\n else:\n nb1c = nb1[\"worksheets\"][0][\"cells\"]\n if \"cells\" in nb2:\n nb2c = nb2[\"cells\"]\n else:\n nb2c = nb2[\"worksheets\"][0][\"cells\"]\n\n # Notebooks do not match if the number of cells differ\n if len(nb1c) != len(nb2c):\n return False\n\n # Iterate over cells in nb1\n for n in range(len(nb1c)):\n # Notebooks do not match if corresponding cells have different\n # types\n if nb1c[n][\"cell_type\"] != nb2c[n][\"cell_type\"]:\n return False\n # Notebooks do not match if source of corresponding code cells\n # differ\n if nb1c[n][\"cell_type\"] == \"code\" and nb1c[n][\"source\"] != nb2c[n][\"source\"]:\n return False\n\n return True\n\n\ndef same_notebook_markdown(nb1, nb2):\n \"\"\"Return ``True`` if the markdown cells of notebook objects `nb1`\n and `nb2` are all the same.\n \"\"\"\n\n if \"cells\" in nb1:\n nb1c = nb1[\"cells\"]\n else:\n nb1c = nb1[\"worksheets\"][0][\"cells\"]\n if \"cells\" in nb2:\n nb2c = nb2[\"cells\"]\n else:\n nb2c = nb2[\"worksheets\"][0][\"cells\"]\n\n # Notebooks do not match if the number of cells differ\n if len(nb1c) != len(nb2c):\n return False\n\n # Iterate over cells in nb1\n for n in range(len(nb1c)):\n # Notebooks do not match if corresponding cells have different\n # types\n if nb1c[n][\"cell_type\"] != nb2c[n][\"cell_type\"]:\n return False\n # Notebooks do not match if source of corresponding code cells\n # differ\n if nb1c[n][\"cell_type\"] == \"markdown\" and nb1c[n][\"source\"] != nb2c[n][\"source\"]:\n return False\n\n return True\n\n\ndef replace_markdown_cells(src, dst):\n \"\"\"Overwrite markdown cells in notebook object `dst` with corresponding\n cells in notebook object `src`.\n \"\"\"\n\n if \"cells\" in src:\n srccell = src[\"cells\"]\n else:\n srccell = src[\"worksheets\"][0][\"cells\"]\n if \"cells\" in dst:\n dstcell = dst[\"cells\"]\n else:\n dstcell = dst[\"worksheets\"][0][\"cells\"]\n\n # It is an error to attempt markdown replacement if src and dst\n # have different numbers of cells\n if len(srccell) != len(dstcell):\n raise ValueError(\"Notebooks do not have the same number of cells.\")\n\n # Iterate over cells in src\n for n in range(len(srccell)):\n # It is an error to attempt markdown replacement if any\n # corresponding pair of cells have different type\n if srccell[n][\"cell_type\"] != dstcell[n][\"cell_type\"]:\n raise ValueError(\"Cell number %d of different type in src and dst.\")\n # If current src cell is a markdown cell, copy the src cell to\n # the dst cell\n if srccell[n][\"cell_type\"] == \"markdown\":\n dstcell[n][\"source\"] = srccell[n][\"source\"]\n","sub_path":"examples/jnb.py","file_name":"jnb.py","file_ext":"py","file_size_in_byte":7601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"32953266","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 6 11:57:27 2019\nUse this code to edit figures saved using pickle dump\n@author: anantgupta\n\"\"\"\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pickle as pl\nimport numpy as np\nfrom matplotlib.ticker import FormatStrFormatter\n\nparams = {\n 'axes.labelsize': 8, # fontsize for x and y labels (was 10)\n 'axes.titlesize': 8,\n# 'text.fontsize': 8, # was 10\n 'legend.fontsize': 7, # was 10\n 'xtick.labelsize': 8,\n 'ytick.labelsize': 8, # 'backend': 'ps',\n 'text.usetex': True,# 'text.latex.preamble': ['\\\\usepackage{gensymb}'],\n 'font.size': 8,\n 'font.family': 'serif',\n 'figure.dpi': 300,\n 'savefig.dpi': 300,\n 'grid.linestyle':':', # dotted\n 'grid.linewidth':0.4, # in points\n 'lines.linewidth':0.5,\n 'lines.markersize' : 2,\n 'lines.markeredgewidth':0.4\n}\nmpl.rcParams.update(params)\n\n# Load figure from disk and display\nif True:\n width = 3.45\n golden_mean = (np.sqrt(5)-1.0)/2.0\n height = 1.6*width*golden_mean\n font_size = 8\n #fig_handle = pl.load(open('results6_14/fig_obj_est2/plot4.pickle','rb'))\n fig_handle1 = pl.load(open('SAGA/fig_pmiss-rob1/plot10.pickle','rb'))\n fig_handle2 = pl.load(open('SAGA/fig_pmiss-rob2/plot10.pickle','rb'))\n fig_handle3 = pl.load(open('SAGA/fig_pmiss-rob8/plot10.pickle','rb'))\n fig_handle4 = pl.load(open('SAESL/fig_pmiss-rob8/plot10.pickle','rb'))\n\n fig_handle1b = pl.load(open('SAGA/fig_pmiss-rob1/plot3.pickle','rb'))\n fig_handle2b = pl.load(open('SAGA/fig_pmiss-rob2/plot3.pickle','rb'))\n fig_handle3b = pl.load(open('SAGA/fig_pmiss-rob8/plot3.pickle','rb'))\n fig_handle4b = pl.load(open('SAESL/fig_pmiss-rob8/plot3.pickle','rb')) \n fha = [fig_handle1, fig_handle2, fig_handle3,fig_handle4]\n fhab = [fig_handle1b, fig_handle2b, fig_handle3b,fig_handle4b]\n colr = ['r','b','g','m']\n mkr = [',','.','x','v']\n ls = ['-','--',':']\n #fig_handle3 = pl.load(open('fig_snr-Nob21/plot2.pickle','rb'))\n lbl=fig_handle1.axes[0].get_legend().get_texts()\n p2lbl = [r'SAGA, $\\rho=1$',r'SAGA, $\\rho=2$',r'SAGA, $\\rho=4$',r'SAESL, $\\rho=4$']\n fig, axa = plt.subplots(2,1)\n ax=axa[0]\n mse1=[0]*4;mse2=[0]*4;mse3=[0]*4;mse4=[0]*4;mse5=[0]*4\n for i in range(2):\n rng2 = fha[i].axes[1].lines[0].get_data()[0]\n for j in range(4):\n rng = fha[2+i].axes[0].lines[2*j].get_data()[0]\n mse1 = fha[2+i].axes[0].lines[2*j].get_data()[1]\n if i==0:\n ax.plot(rng, mse1,colr[j]+mkr[i]+ls[i], label = r'$P_{miss}=$'+'{:0.2f}'.format(rng2[2*j]))\n else:\n ax.plot(rng, mse1,colr[j]+mkr[i]+ls[i])\n ax.legend(loc='best')\n ax.grid(True);\n \n # ax[i].set_title(fig_handle1.axes[2*i].get_title())\n ax.set_ylabel(fig_handle1.axes[0].get_ylabel())\n ax.set_xlabel(fig_handle1.axes[0].get_xlabel())\n ax.set_title(r'Graph size v/s iterations')\n \n # for i in range(4): \n # rng2 = fhab[i].axes[2].lines[0].get_data()[0]\n # mse2 = fhab[i].axes[2].lines[0].get_data()[1]\n # axa[1].plot(rng2, mse2, marker=mkr[i], linestyle=ls[i==2], label=p2lbl[i])\n \n # # axa[1].plot(rng2, 20-fha[i].axes[1].lines[1].get_data()[1], 'k:',label='true')\n\n # axa[1].set_ylabel(r'$N_T-N_e$')\n # axa[1].set_xlabel(r'$P_{miss}$') \n # axa[1].legend(loc='best')\n # axa[1].grid(True);\n \n # axa[1].set_title(r'Cardinality Error')\n ax3=1\n for i in range(4): \n rng2 = fhab[i].axes[0].lines[0].get_data()[0]\n mse2 = fhab[i].axes[0].lines[0].get_data()[1]\n axa[ax3].plot(rng2, mse2, marker=mkr[i], linestyle=ls[i==3], label=p2lbl[i])\n # axa[2].plot(rng2, fhab[i].axes[0].lines[0].get_data()[1], 'k:',label='true')\n axa[ax3].set_ylabel(r'OSPA')\n axa[ax3].set_xlabel(r'$P_{miss}$') \n axa[ax3].legend(loc='best')\n axa[ax3].grid(True);\n axa[ax3].set_yscale('log')\n axa[ax3].set_title(r'OSPA')\n\n # ax[1].set_ylim(-4,12)\n fig.set_size_inches(width, height, forward=True)\n # v--- change title and axeslabel font sizes manually\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n ax.get_xticklabels() + ax.get_yticklabels()):\n item.set_fontsize(font_size)\n \n# ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))\n# ax.yaxis.set_minor_formatter(None)\n# plt.yticks([0.2,0.3,0.4,0.6,1])\n # ax[1].yaxis.set_major_formatter(FormatStrFormatter('%.0f'))\n plt.tight_layout()\n fig.set_tight_layout(True)\n pl.dump(fig, open(\"Graph_nodes_vs_pmiss.pickle\", \"wb\"))\n fig.savefig('Graph_nodes_vs_pmiss.pdf')","sub_path":"TSP19simpack/paper_plots/plotting_scripts/Fig5_Pmiss.py","file_name":"Fig5_Pmiss.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502963477","text":"import os\nimport logging\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nlogger = logging.getLogger(\"database.py\")\nlogger.setLevel(logging.INFO)\n\n\nmetadata = MetaData()\nBase = declarative_base(metadata=metadata)\n\n\ndef get_db_session():\n return DatabaseManager().get_db_session()\n\n\ndef dsn_from_env():\n \"\"\"returns dsn suitable to pass to sqlalchemy's create_engine\n if env var SQLALCHEMY_DSN is found, it will be used, else composite vars\n are examined (note at least SQLALCHEMY_DBNAME is required):\n * SQLALCHEMY_SCHEME (default=postgres)\n * SQLALCHEMY_HOST (default=localhost)\n * SQLALCHEMY_PORT (default=5432)\n * SQLALCHEMY_DBNAME (no default; required)\n * SQLALCHEMY_USER (no default; required for authed access to db)\n * SQLALCHEMY_PASS (no default; required for authed access to db)\n \"\"\"\n dsn = os.environ.get(\"SQLALCHEMY_DSN\", \"\")\n # For local use only\n # Deployed code gets it from environment\n dsn = \"postgresql://currentapi:Current123!@aa8og5oo6hypyq.cm3yh0naog66.us-east-1.rds.amazonaws.com:5432/current_api_v1\"\n if not dsn:\n scheme = os.environ.get(\"SQLALCHEMY_SCHEME\", \"postgres\")\n host = os.environ.get(\"SQLALCHEMY_HOST\", \"localhost\")\n port = os.environ.get(\"SQLALCHEMY_PORT\", \"5432\")\n dbname = os.environ.get(\"SQLALCHEMY_DBNAME\", \"\")\n user = os.environ.get(\"SQLALCHEMY_USER\", \"\")\n pwd = os.environ.get(\"SQLALCHEMY_PASS\", \"\")\n if not dbname:\n raise ValueError(\"SQLALCHEMY_DSN or SQLALCHEMY_DBNAME is required\")\n auth = \"{}:{}@\".format(user, pwd) if user and pwd else \"\"\n if not auth:\n logger.warning(\"DB auth not configured\")\n dsn = \"{}://{}{}:{}/{}\".format(scheme, auth, host, port, dbname)\n logger.info(\"dsn_from_env: {}\".format(dsn))\n return dsn\n\n\nclass DatabaseManager(object):\n def __new__(self):\n \"\"\"\n Creates a Singleton Class for Database\n \"\"\"\n if not hasattr(self, \"instance\"):\n self.instance = super().__new__(self)\n return self.instance\n\n def __init__(self):\n if not hasattr(self, \"engine\"):\n logger.info(\"creating a new DB Engine\")\n self.engine = self.create_db_engine()\n\n @staticmethod\n def create_db_engine():\n return create_engine(dsn_from_env(), echo=True, pool_size=10, max_overflow=10)\n\n def get_db_session(self):\n session = sessionmaker()\n session.configure(bind=self.engine)\n db_session = session()\n return db_session\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"275912117","text":"# \n# TestProtocol.py\n#\n# Unit tests for the tesla.types.Protocol class\n# \n# Copyright (c) Invetech Pty Ltd, 2004\n# 495 Blackburn Rd\n# Mt Waverley, Vic, Australia.\n# Phone (+61 3) 9211 7700\n# Fax (+61 3) 9211 7701\n# \n# The copyright to the computer program(s) herein is the\n# property of Invetech Pty Ltd, Australia.\n# The program(s) may be used and/or copied only with\n# the written permission of Invetech Pty Ltd\n# or in accordance with the terms and conditions\n# stipulated in the agreement/contract under which\n# the program(s) have been supplied.\n# \n\nimport unittest\nimport os\nimport handyxml\n\nimport tesla.config\nfrom tesla.exception import TeslaException\nfrom tesla.types.Command import *\nfrom tesla.types.Protocol import Protocol, ProtocolException\nfrom tesla.types.ProtocolConsumable import ProtocolConsumable, EMPTY, NOT_NEEDED\nfrom tesla.types.sample import Sample\n\n# -------------------------------------------------------------------------\n# Support function to allow us to generate XML nodes straight from a string\n# (rather than from a file)\n\nfrom xml.dom.ext.reader import PyExpat\n\ndef xmlFromString(xmldata):\n \"\"\" Parse some XML from a string.\n The return value is the parsed XML as DOM nodes.\n \"\"\"\n doc = PyExpat.Reader().fromString(xmldata)\n parsedxml = handyxml.HandyXmlWrapper(doc.documentElement)\n return parsedxml\n\n# -------------------------------------------------------------------------\n\nclass TestProtocol(unittest.TestCase):\n\n def setUp(self):\n testFile = 'test_maintenance.xml'\n self.fileName = os.path.join(tesla.config.PROTOCOL_DIR, testFile)\n self.p = Protocol(fileName = self.fileName)\n\n def test_file(self):\n self.failUnless(self.p, 'Testing file existence and Protocol instance creation')\n self.failUnless(self.fileName == self.p.sourceFile, 'Testing filename')\n\n def test_nonExistentFile(self):\n # This XML file should not exist and we should catch an exception\n absentFile = 'groundeffect.xml'\n self.assertRaises(ProtocolException, Protocol, absentFile)\n\n def test_ID(self):\n self.failUnless(self.p.ID)\n self.failUnless(type(self.p.ID) == int, 'Testing ID type (should be int)')\n\n def test_type(self):\n self.failUnless(self.p.type == 'Maintenance', 'Testing type of protocol')\n\n def test_parseHeaderNode(self):\n label = 'My header test protocol'\n version = '1999'\n created = '2004-01-07'\n modified = '2004-12-25'\n author = 'Banjo Patterson'\n\n headerData = \\\n \"\"\"
\n \n \n
\n \"\"\" % (label, version, created, modified, author,)\n \n headerNode = xmlFromString(headerData)\n self.p.parseHeaderNode(headerNode)\n self.failUnless(self.p.label == label, 'Testing label field')\n self.failUnless(self.p.version == version, 'Testing version field')\n self.failUnless(self.p.created == created, 'Testing created field')\n self.failUnless(self.p.modified == modified, 'Testing modified field')\n self.failUnless(self.p.author == author, 'Testing author field')\n \n\n def createHeaderString(self, label):\n # create a header string with the supplied label\n version = '1999'\n created = '2004-01-07'\n modified = '2004-12-25'\n author = 'Banjo Patterson'\n\n return \\\n \"\"\"
\n \n \n
\n \"\"\" % (label, version, created, modified, author,)\n \n\n def test_parseHeaderNode(self):\n label = 'My header test protocol'\n headerData = self.createHeaderString(label)\n headerNode = xmlFromString(headerData)\n self.p.parseHeaderNode(headerNode)\n self.failUnless(self.p.label == label, 'Testing label field')\n self.failUnless(self.p.version, 'Testing version field')\n self.failUnless(self.p.created, 'Testing created field')\n self.failUnless(self.p.modified, 'Testing modified field')\n self.failUnless(self.p.author, 'Testing author field') \n\n\n def test_labelsWithSpaces(self):\n # Labels with leading/trailing \n realLabel = 'foobar'\n for label in (' ' + realLabel, realLabel, realLabel + ' '):\n headerData = self.createHeaderString(label)\n headerNode = xmlFromString(headerData)\n self.p.parseHeaderNode(headerNode)\n self.failUnless(self.p.label == realLabel, 'Testing trimmed label field') \n \n\n def test_parseConstraintsNode_SeparationConstraints(self):\n quads = 1\n minVol, maxVol = 1000, 10000\n threshold = 2500\n lowVol, highVol = 5000, 10000\n \n data = \\\n \"\"\"\n \n \n \n \n \n \"\"\" % (quads, minVol, maxVol, threshold, lowVol, highVol)\n \n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.numQuadrants == quads, 'Testing number of quadrants')\n self.failUnless(self.p.minVol == minVol, 'Testing min sample volume')\n self.failUnless(self.p.maxVol == maxVol, 'Testing max sample volume')\n self.failUnless(self.p.sampleThreshold == threshold, 'Testing sample threshold')\n self.failUnless(self.p.lowWorkingVolume == lowVol, 'Testing low working volume')\n self.failUnless(self.p.highWorkingVolume == highVol, 'Testing high working volume') \n\n def test_parseConstraintsNode_MaintenanceConstraints(self):\n quads = 0\n data = \\\n \"\"\"\n \n \n \n \"\"\" % (quads)\n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.numQuadrants == quads, 'Testing number of quadrants')\n # All these should reset to zero\n self.failUnless(self.p.minVol == 0, 'Testing min sample volume')\n self.failUnless(self.p.maxVol == 0, 'Testing max sample volume')\n self.failUnless(self.p.sampleThreshold == 0, 'Testing sample threshold')\n self.failUnless(self.p.lowWorkingVolume == 0, 'Testing low working volume')\n self.failUnless(self.p.highWorkingVolume == 0, 'Testing high working volume') \n \n\n def test_parseConstraintsNode_SwappedMinMaxVolumes(self):\n minVol, maxVol = 9000, 500\n data = \\\n \"\"\"\n \n \n \n \n \n \"\"\" % (minVol, maxVol)\n \n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.minVol == maxVol, 'Testing swapped min sample volume')\n self.failUnless(self.p.maxVol == minVol, 'Testing swapped max sample volume')\n\n\n def test_parseConstraintsNode_SwappedWorkingVolumes(self):\n lowVol, highVol = 9000, 5000\n data = \\\n \"\"\"\n \n \n \n \n \n \"\"\" % (lowVol, highVol)\n \n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.lowWorkingVolume == highVol, 'Testing swapped low working volume')\n self.failUnless(self.p.highWorkingVolume == lowVol, 'Testing swapped high working volume')\n\n\n def test_parseConstraintsNode_InvalidLowVolume(self):\n threshold = 1000\n lowVol, highVol = 500, 8000\n data = \\\n \"\"\"\n \n \n \n \n \n \"\"\" % (threshold, lowVol, highVol)\n \n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.sampleThreshold == lowVol , 'Testing new sample threshold')\n self.failUnless(self.p.lowWorkingVolume == lowVol, 'Testing low working volume')\n self.failUnless(self.p.highWorkingVolume == highVol, 'Testing high working volume')\n\n\n def test_parseConstraintsNode_InvalidMaxVolume(self):\n maxVol = 12000\n threshold = 1000\n lowVol, highVol = 5000, 8000\n data = \\\n \"\"\"\n \n \n \n \n \n \"\"\" % (maxVol, threshold, lowVol, highVol)\n \n node = xmlFromString(data)\n self.p.parseConstraintsNode(node)\n self.failUnless(self.p.maxVol == highVol, 'Testing new max volume')\n\n\n def test_parseConstraintsNode_BadQuadrants(self):\n quads = 42\n data = \\\n \"\"\"\n \n \n \n \"\"\" % (quads)\n node = xmlFromString(data)\n self.assertRaises(AttributeError, self.p.parseConstraintsNode, node)\n\n\n def test_commands(self):\n cmds1 = self.p.getCommands()\n cmds2 = self.p.getCommands()\n\n self.failUnless(len(cmds1) > 1)\n self.failUnless(len(cmds1) == len(cmds2))\n cmds2.pop()\n self.failUnless(len(cmds1) == len(cmds2) + 1, 'Testing decoupled lists')\n\n\n def test_command(self):\n for i in [1, 2]:\n # Expect two commands\n cmd = self.p.getCommand(i)\n self.failUnless(isinstance(cmd, Command), 'Testing Command instance')\n # Shouldn't be able to get commands outside of the first two\n self.assertRaises(ProtocolException, self.p.getCommand, 0)\n self.assertRaises(ProtocolException, self.p.getCommand, 99)\n\n\n def test_types(self):\n # Check the type of key members\n intType = type(1)\n self.failUnless(type(self.p.numQuadrants) == intType)\n self.failUnless(type(self.p.minVol) == intType)\n self.failUnless(type(self.p.maxVol) == intType)\n self.failUnless(type(self.p.sampleThreshold) == intType)\n self.failUnless(type(self.p.lowWorkingVolume) == intType)\n self.failUnless(type(self.p.highWorkingVolume) == intType)\n\n self.failUnless(isinstance(self.p.cmds, list), 'Testing commands class')\n\n\n def test_getVolumes(self):\n baseName = 'test_OneLiner.xml' \n fileName = os.path.join(tesla.config.PROTOCOL_DIR, baseName)\n pro = Protocol(fileName)\n self.failUnless(pro)\n \n volume = 1000\n vols = pro.getVolumes(volume)\n self.failUnless(type(vols) == list)\n self.failUnless(len(vols) == pro.numQuadrants, 'Expect just one quadrant of consumables')\n pcs = vols[0]\n\n self.failUnless(isinstance(pcs, ProtocolConsumable))\n self.failUnless(pcs.quadrant == 1, 'Expect to be in the first quadrant')\n\n self.failUnless(pcs.tipBoxRequired, 'We need a tip box')\n self.failUnless(pcs.sampleVesselRequired, 'We need a sample vessel')\n self.failIf(pcs.separationVesselRequired, \"We don't need a separation vessel\")\n self.failUnless(pcs.cocktailVolume > 0, 'We need cocktail')\n self.failUnless(pcs.bulkBufferVolume == NOT_NEEDED, \"We don't need BCCM\")\n self.failUnless(pcs.particleVolume == NOT_NEEDED, \"We don't need particles\")\n self.failUnless(pcs.antibodyVolume == NOT_NEEDED, \"We don't need antibody\")\n self.failUnless(pcs.lysisVolume == NOT_NEEDED, \"We don't need lysis\")\n\n\n def test_getVolumes2(self):\n baseName = 'TestTransport.xml'\n ''' \n fileName = os.path.join(tesla.config.PROTOCOL_DIR, baseName)\n pro = Protocol(fileName)\n self.failUnless(pro)\n \n volume = 2000\n vols = pro.getVolumes(volume)\n self.failUnless(type(vols) == list)\n pcs = vols[0]\n \n self.failUnless(isinstance(pcs, ProtocolConsumable))\n self.failUnless(pcs.quadrant == 1, 'Expect to be in the first quadrant')\n\n self.failUnless(pcs.tipBoxRequired, 'We need a tip box')\n self.failUnless(pcs.sampleVesselRequired, 'We need a sample vessel')\n self.failUnless(pcs.separationVesselRequired, 'We need a separation vessel')\n self.failUnless(pcs.wasteVesselRequired, 'We need a waste vessel')\n \n self.failUnless(pcs.cocktailVolume > 0, 'We need cocktail')\n self.failUnless(pcs.bulkBufferVolume > 0, \"We need BCCM\")\n self.failUnless(pcs.particleVolume == NOT_NEEDED, \"We don't need particles\")\n self.failUnless(pcs.antibodyVolume == NOT_NEEDED, \"We don't need antibody\")\n self.failUnless(pcs.lysisVolume == NOT_NEEDED, \"We don't need lysis\")\n\n # print pcs.getPrettyString()\n '''\n \n def test_theLot(self):\n '''Test the protocol (and commands) using our test protocol.''' \n baseName = 'test_protocol.xml'\n fileName = os.path.join(tesla.config.PROTOCOL_DIR, baseName)\n pro = Protocol(fileName)\n self.failUnless(pro)\n\n sample = Sample(42, 'Test sample', pro.ID, 1250, 1)\n self.failUnless(sample, 'Testing sample creation')\n\n cmds = pro.getCommands()\n self.failUnless(len(cmds) == pro.numCmds, 'Testing number of commands')\n\n expectedSeq = 1\n for cmd in cmds:\n self.failUnless(cmd.isLegal(), \"Testing that %s command is legal\" % (cmd))\n self.failUnless(cmd.label)\n self.failUnless(type(cmd.seq) == int, 'Testing sequence number type')\n self.failUnless(cmd.seq == expectedSeq)\n expectedSeq += 1\n\n if cmd.isMixType():\n pass\n \n elif cmd.isServiceType():\n if isinstance(cmd, DemoCommand):\n self.failUnless(type(cmd.iterations) == int)\n self.failUnless(cmd.iterations > 0)\n \n elif cmd.isTransportType():\n self.failUnless(cmd.freeAirDispense in [True, False])\n self.failUnless(cmd.useBufferTip in [True, False])\n self.failUnless(cmd.srcVial != None)\n self.failUnless(cmd.destVial != None)\n if cmd.relative:\n self.failUnless(cmd.proportion > 0.0)\n else:\n self.failUnless(cmd.absVolume >= 0)\n \n elif cmd.isVolumeType():\n self.failUnless(cmd.srcVial != None)\n self.failUnless(cmd.destVial != None)\n \n elif cmd.isWaitType():\n self.failUnless(cmd.minPeriod >= 0)\n \n else:\n self.fail(\"%s is an unknown command type\" % (cmd))\n \n call = cmd.createCall(sample, pro)\n self.failUnless(cmd)\n # Note -- should put more testing in here...\n \n\n# -----------------------------------------------------------------------------\n\nif __name__ == '__main__':\n unittest.main()\n\n# eof\n","sub_path":"Server/tesla/types/tests/TestProtocol.py","file_name":"TestProtocol.py","file_ext":"py","file_size_in_byte":15694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"611549713","text":"import pandas as pd\nfrom dataiku import Dataset\nimport logging\nfrom dataiku.doctor import utils\n\ndef df_from_split_desc_no_normalization(split_desc, split, feature_params, prediction_type=None):\n if split_desc[\"format\"] != \"csv1\":\n raise Exception(\"Unsupported format\")\n (names, dtypes, parse_date_columns) = Dataset.get_dataframe_schema_st(\n split_desc[\"schema\"][\"columns\"], parse_dates=True, infer_with_pandas=True)\n\n if split == \"full\":\n f = split_desc[\"fullPath\"]\n else:\n f = split == \"train\" and split_desc[\"trainPath\"] or split_desc[\"testPath\"]\n\n # We infer everything with Pandas, EXCEPT booleans.\n # Because then pandas completely looses the original syntax\n # So for example if target is true/false, and we let pandas infer, then it will become\n # True/False, and when we remap, we try to remap with true/false and end up with no\n # target at all\n # for col in split_desc[\"schema\"][\"columns\"]:\n # if col[\"type\"] == \"boolean\":\n # if dtypes is None:\n # dtypes = {}\n # dtypes[col[\"name\"]] = \"str\"\n\n\n logging.info(\"Reading with dtypes: %s\" % dtypes)\n dtypes = utils.ml_dtypes_from_dss_schema(split_desc[\"schema\"], feature_params,\n prediction_type = prediction_type)\n\n logging.info(\"Reading with FIXED dtypes: %s\" % dtypes)\n df = pd.read_table(f,\n names=names,\n dtype=dtypes,\n header=None,\n sep='\\t',\n doublequote=True,\n quotechar='\"',\n parse_dates=parse_date_columns,\n float_precision=\"round_trip\")\n logging.info(\"Loaded table\")\n \n return df\n\ndef df_from_split_desc(split_desc, split, feature_params, prediction_type=None):\n df = df_from_split_desc_no_normalization(split_desc, split, feature_params, prediction_type)\n return utils.normalize_dataframe(df, feature_params)","sub_path":"python/dataiku/doctor/utils/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"500604958","text":"from flask import Flask, render_template, request, flash, redirect\nfrom flask_mail import Mail, Message\nfrom dotenv import load_dotenv\nimport os\n\n# Loads env variables for email information\nload_dotenv()\napp = Flask(__name__)\napp.secret_key = os.urandom(12)\n\n# Settings for sending me an email notification on contact form submission\nmail_settings = {\n \"MAIL_SERVER\": 'smtp.gmail.com',\n \"MAIL_PORT\": 465,\n \"MAIL_USE_TLS\": False,\n \"MAIL_USE_SSL\": True,\n \"MAIL_USERNAME\": os.environ['EMAIL_USER'],\n \"MAIL_PASSWORD\": os.environ['EMAIL_PASSWORD']\n}\n\napp.config.update(mail_settings)\nmail = Mail(app)\n\n\ndef send(data):\n \"\"\"Sends the data passed in to the email specified in the env variable EMAIL_RECIPIENT\"\"\"\n msg = Message(subject=data['subject'],\n sender=app.config.get(\"MAIL_USERNAME\"),\n recipients=[os.environ['EMAIL_RECIPIENT']],\n body=f\"Email: {data['email']} Body: {data['message']}\")\n mail.send(msg)\n print('Message Sent')\n\n\n@app.route('/')\ndef root():\n \"\"\"Renders index.html\"\"\"\n return render_template('index.html')\n\n\n@app.route('/')\ndef html_page(page_name):\n \"\"\"Renders the passed in page as long as it exists\"\"\"\n return render_template(page_name)\n\n\n@app.route('/submit_form', methods=['POST', 'GET'])\ndef submint_form():\n \"\"\"Takes in the input form and preps the data to be passed to send() and alerts user of submission status. \n In all cases returns a redirect to index.html\"\"\"\n if request.method == 'POST':\n data = request.form.to_dict()\n print(data)\n if data['email'] and data['subject'] and data['message']:\n flash('Form submitted! I will get back to you as soon as I can.')\n send(data)\n return redirect('index.html')\n else:\n flash('Invalid submission')\n return redirect('index.html')\n else:\n flash('Something went wrong with your submission')\n return redirect('index.html')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"205667797","text":"import feedparser\nimport time\nimport tweepy\nimport os\nfrom bs4 import BeautifulSoup\n\n\n\nconsumer_key = os.getenv('consumer_key')\nconsumer_secret = os.getenv('consumer_secret')\n\naccess_token = os.getenv('access_token')\naccess_token_secret = os.getenv('access_token_secret')\n\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\npublic_tweets = api.home_timeline()\n\n\nfeed_url = ('http://8bhomeworkassignments.blogspot.com/feeds/posts/default')\n\noldpublished = (public_tweets[0])\noldpublished = (oldpublished.text)\n\nwhile True:\n\n feed = feedparser.parse(feed_url)\n \n #fixed, see commit desc\n newpublished = (feed['entries'][0]['title'])\n \n #also fixed, see commit desc\n if newpublished not in oldpublished:\n\n # Grabs the newest item from the feed with its title and content\n oldfeed = feedparser.parse(feed_url)\n title = (oldfeed['entries'][0]['title'])\n title = BeautifulSoup(title, \"lxml\").text\n content = (oldfeed['entries'][0]['content'][0]['value'])\n content = BeautifulSoup(content, \"lxml\").text\n\n oldpublished = (oldfeed['entries'][0]['published'])\n\n print (title)\n print (content)\n\n tweetthis = (title + '\\n' + content)\n api.update_status(tweetthis)\n\n #also fixed, see commit desc\n elif newpublished in oldpublished:\n\n print ('Nothing new...')\n\n\n time.sleep(5)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"441772636","text":"import numpy as np\nfrom sklearn.base import clone\nimport copy\n\n\nclass EntingRegressor:\n \"\"\"Predict with LightGBM tree model and include model uncertainty \n defined by distance-based standard estimator.\n\n\n Parameters\n ----------\n base_estimator : LGBMRegressor instance, EntingRegressor instance or \n None (default). If LGBMRegressor instance of None is given: new \n EntingRegressor is defined. If EntingRegressor is given: base_estimator\n and std_estimator are given to new instance.\n std_estimator : DistanceBasedStd instance,\n Determines which measure is used to capture uncertainty.\n random_state : int, RandomState instance, or None (default)\n Set random state to something other than None for reproducible\n results.\n \"\"\"\n\n def __init__(self,\n space,\n base_estimator,\n std_estimator,\n random_state:int = None,\n cat_idx=None):\n\n if cat_idx is None:\n cat_idx = []\n\n np.random.seed(random_state)\n\n self.random_state = random_state\n self.space = space\n self.base_estimator = base_estimator\n self.std_estimator = std_estimator\n self.cat_idx = cat_idx\n self.num_obj = len(self.base_estimator)\n\n # check if base_estimator is EntingRegressor\n if isinstance(base_estimator[0], EntingRegressor):\n self.base_estimator = base_estimator.base_estimator\n self.std_estimator = base_estimator.std_estimator\n\n def fit(self, X, y):\n \"\"\"Fit model and standard estimator to observations.\n\n Parameters\n ----------\n X : array-like, shape=(n_samples, n_features)\n Training vectors, where `n_samples` is the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape=(n_samples,)\n Target values (real numbers in regression)\n\n Returns\n -------\n -\n \"\"\"\n self.regressor_ = []\n y = np.asarray(y)\n self._y = y\n\n for i,est in enumerate(self.base_estimator):\n # suppress lgbm output\n est.set_params(\n random_state=self.random_state,\n verbose=-1\n )\n\n # clone base_estimator (only supported for sklearn estimators)\n self.regressor_.append(clone(est))\n\n # update std estimator\n self.std_estimator.update(X, y, cat_column=self.cat_idx)\n\n # update tree model regressor\n import warnings\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n if self.num_obj > 1:\n if self.cat_idx:\n self.regressor_[-1].fit(X, y[:,i], categorical_feature=self.cat_idx)\n else:\n self.regressor_[-1].fit(X, y[:,i])\n else:\n if self.cat_idx:\n self.regressor_[-1].fit(X, y, categorical_feature=self.cat_idx)\n else:\n self.regressor_[-1].fit(X, y)\n\n def set_params(self, **params):\n \"\"\"Sets parameters related to tree model estimator. All parameter \n options for LightGBM are given here: \n https://lightgbm.readthedocs.io/en/latest/Parameters.html\n\n Parameters\n ----------\n kwargs : dict\n Additional arguments to be passed to the tree model\n\n Returns\n -------\n -\n \"\"\"\n if not \"min_child_samples\" in params:\n params.update({\"min_child_samples\":2})\n\n for i in range(len(self.base_estimator)):\n self.base_estimator[i].set_params(**params)\n\n def predict(self, X, return_std=False):\n \"\"\"Predict.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n where `n_samples` is the number of samples\n and `n_features` is the number of features.\n return_std: boolean, If `return_std` is set to False, only tree model prediction is returned. If set to True,\n tree model prediction and predicted standard deviation is returned.\n\n Returns\n -------\n mean or (mean, std): np.array, shape (n_rows, n_dims) \n or tuple(np.array, np.array), depending on value of `return_std`.\n \"\"\"\n\n if self.num_obj == 1:\n mean = self.regressor_[0].predict(X)\n else:\n mean = []\n for tree in self.regressor_:\n mean.append(tree.predict(X))\n\n if return_std:\n std = self.std_estimator.predict(X)\n return mean, std\n\n # return the mean\n return mean\n\n def get_gbm_model(self):\n \"\"\"\n Returns `GbmModel` instance of the tree model.\n\n Parameters\n ----------\n -\n\n Returns\n -------\n gbm_model : `GbmModel`\n ENTMOOT native tree model format to formulate optimization model\n \"\"\"\n\n from entmoot.learning.lgbm_processing import order_tree_model_dict\n from entmoot.learning.gbm_model import GbmModel\n gbm_model_dict = {}\n for i,tree in enumerate(self.regressor_):\n original_tree_model_dict = tree._Booster.dump_model()\n\n # import json\n # with open('tree_dict_next.json', 'w') as f:\n # json.dump(\n # original_tree_model_dict,\n # f,\n # indent=4,\n # sort_keys=False\n # )\n\n ordered_tree_model_dict = \\\n order_tree_model_dict(\n original_tree_model_dict,\n cat_column=self.cat_idx\n )\n\n gbm_model_dict[i] = GbmModel(ordered_tree_model_dict)\n return gbm_model_dict\n\n def get_global_next_x(self,\n acq_func,\n acq_func_kwargs,\n add_model_core,\n weight,\n verbose,\n gurobi_env,\n gurobi_timelimit,\n has_unc=True):\n from entmoot.optimizer.gurobi_utils import \\\n get_core_gurobi_model, add_gbm_to_gurobi_model, \\\n add_std_to_gurobi_model, add_acq_to_gurobi_model, \\\n set_gurobi_init_to_ref, get_gbm_multi_obj_from_model\n\n # suppress output to command window\n import logging\n logger = logging.getLogger()\n logger.setLevel(logging.CRITICAL)\n\n # start building model\n gurobi_model = \\\n get_core_gurobi_model(\n self.space, add_model_core, env=gurobi_env\n )\n\n if verbose == 2:\n print(\"\")\n print(\"\")\n print(\"\")\n print(\"SOLVER: *** start gurobi solve ***\")\n gurobi_model.Params.LogToConsole = 1\n else:\n gurobi_model.Params.LogToConsole = 0\n\n # convert into gbm_model format\n # and add to gurobi model\n gbm_model_dict = self.get_gbm_model()\n add_gbm_to_gurobi_model(\n self.space, gbm_model_dict, gurobi_model\n )\n\n # add std estimator to gurobi model\n if has_unc:\n add_std_to_gurobi_model(self, gurobi_model)\n\n # collect different objective function contributions\n from entmoot.optimizer.gurobi_utils import get_gbm_model_multi_obj_mu, get_gbm_model_mu\n\n if self.num_obj > 1:\n model_mu = get_gbm_model_multi_obj_mu(gurobi_model, self._y)\n\n if has_unc:\n model_unc = self.std_estimator.get_gurobi_obj(gurobi_model)\n else: model_unc = None\n else:\n model_mu = get_gbm_model_mu(gurobi_model, self._y, norm=False)\n model_unc = self.std_estimator.get_gurobi_obj(gurobi_model)\n\n # add obj to gurobi model\n from opti.sampling.simplex import sample\n\n weight = sample(self.num_obj,1)[0] if weight is None else weight\n\n add_acq_to_gurobi_model(gurobi_model, model_mu, model_unc,\n self,\n weights=weight,\n num_obj=self.num_obj,\n acq_func=acq_func,\n acq_func_kwargs=acq_func_kwargs)\n\n # set initial gurobi model vars to std_est reference points\n if has_unc:\n if self.std_estimator.std_type == 'distance':\n set_gurobi_init_to_ref(self, gurobi_model)\n\n # set gurobi time limit\n if gurobi_timelimit is not None:\n gurobi_model.Params.TimeLimit = gurobi_timelimit\n gurobi_model.Params.OutputFlag = 1\n\n gurobi_model.update()\n gurobi_model.optimize()\n\n assert gurobi_model.SolCount >= 1, \"gurobi couldn't find a feasible \" + \\\n \"solution. Try increasing the timelimit if specified. \" + \\\n \"In case you specify your own 'add_model_core' \" + \\\n \"please check that the model is feasible.\"\n\n # store optimality gap of gurobi computation\n gurobi_mipgap = None\n if acq_func not in [\"HLCB\"]:\n gurobi_mipgap = gurobi_model.mipgap\n\n # for i in range(2): REMOVEX\n # gurobi_model.params.ObjNumber = i\n # # Query the o-th objective value\n # print(f\"{i}:\")\n # print(gurobi_model.ObjNVal)\n\n # output next_x\n next_x = np.empty(len(self.space.dimensions))\n\n # cont features\n for i in gurobi_model._cont_var_dict:\n next_x[i] = gurobi_model._cont_var_dict[i].x\n\n # cat features\n for i in gurobi_model._cat_var_dict:\n cat = \\\n [\n key\n for key in gurobi_model._cat_var_dict[i]\n if int(\n round(gurobi_model._cat_var_dict[i][key].x, 1)\n ) == 1\n ]\n\n next_x[i] = cat[0]\n\n model_mu = get_gbm_multi_obj_from_model(gurobi_model)\n if has_unc:\n model_std = gurobi_model._alpha.x\n else:\n model_std = None\n\n return next_x, model_mu, model_std, gurobi_mipgap\n\n def copy(self):\n return copy.copy(self)\n\n\nclass MisicRegressor(EntingRegressor):\n\n def __init__(self,\n space,\n base_estimator=None,\n std_estimator=None,\n random_state=None,\n cat_idx=None):\n\n if cat_idx is None:\n cat_idx = []\n\n self.random_state = random_state\n self.space = space\n self.base_estimator = base_estimator\n self.std_estimator = std_estimator\n self.cat_idx = cat_idx\n self.num_obj = len(self.base_estimator)\n\n # check if base_estimator is EntingRegressor\n if isinstance(base_estimator, MisicRegressor):\n self.base_estimator = base_estimator.base_estimator\n self.std_estimator = base_estimator.std_estimator\n\n def fit(self, X, y):\n \"\"\"Fit model and standard estimator to observations.\n\n Parameters\n ----------\n X : array-like, shape=(n_samples, n_features)\n Training vectors, where `n_samples` is the number of samples\n and `n_features` is the number of features.\n\n y : array-like, shape=(n_samples,)\n Target values (real numbers in regression)\n\n Returns\n -------\n -\n \"\"\"\n self.regressor_ = []\n y = np.asarray(y)\n self._y = y\n\n for i,est in enumerate(self.base_estimator):\n # suppress lgbm output\n est.set_params(\n random_state=self.random_state,\n verbose=-1\n )\n\n # clone base_estimator (only supported for sklearn estimators)\n self.regressor_.append(clone(est))\n\n # update tree model regressor\n import warnings\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n if self.num_obj > 1:\n if self.cat_idx:\n self.regressor_[-1].fit(X, y[:,i], categorical_feature=self.cat_idx)\n else:\n self.regressor_[-1].fit(X, y[:,i])\n else:\n if self.cat_idx:\n self.regressor_[-1].fit(X, y, categorical_feature=self.cat_idx)\n else:\n self.regressor_[-1].fit(X, y)\n\n gbm_model = self.get_gbm_model()[0]\n\n # update std estimator\n self.std_estimator.update(X, y, gbm_model, cat_column=self.cat_idx)\n","sub_path":"entmoot/learning/tree_model.py","file_name":"tree_model.py","file_ext":"py","file_size_in_byte":12903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"425323741","text":"#!/usr/bin/env python3\nimport time\n\nfrom bubblesort_api import bubble_sort\nfrom insertionsort_api import insertion_sort\nfrom selectionsort_api import selection_sort\nfrom quicksort_api import quick_sort\n\nFILENAMES = [\n [ 'list1.txt', 'int' ],\n [ 'list2.txt', 'int' ],\n [ 'list3.txt', 'int' ],\n [ 'list4.txt', 'int' ],\n [ 'list5.txt', 'float' ],\n [ 'list6.txt', 'int' ],\n]\n\n\nclass Result:\n def __init__(self, name, duration, nums):\n self.name = name\n self.duration = duration\n self.nums = nums\n self.relative = None\n\ndef print_results(list_name, results):\n print(list_name)\n for result in results:\n print(result.name)\n print(result.duration)\n print('{}%'.format(result.relative))\n print('First 10: {}'.format(', '.join([ str(item) for item in result.nums[:10] ])))\n print('Last 10: {}'.format(', '.join([ str(item) for item in result.nums[-10:] ])))\n print()\n\n\ndef determine_fastest(results):\n fastest = results[0].duration\n for i in range(len(results) - 1):\n if fastest > results[i].duration:\n fastest = results[i].duration\n\n return fastest\n\ndef calculate_relative(results, fastest):\n for result in results:\n result.relative = round(100.0 * (result.duration - fastest) / fastest)\n return results\n\n\ndef main():\n for i in FILENAMES:\n results = []\n with open(i[0], 'r') as file:\n list_name = i[0]\n text = file.read()\n numbers = text.split()\n if i[1] == 'int':\n numbers = [ int(x) for x in numbers ]\n elif i[1] == 'float':\n numbers = [ float(x) for x in numbers ]\n\n # Native sort\n one_thousand = []\n for i in range(1000):\n one_thousand.append(numbers[:])\n\n start = time.time()\n for i in one_thousand:\n i.sort()\n duration = round(time.time() - start, 6)\n results.append(Result('Native Language Sort', duration, i))\n\n # Bubble sort\n one_thousand = []\n for i in range(1000):\n one_thousand.append(numbers[:])\n\n start = time.time()\n for i in one_thousand:\n sorted_numbers = bubble_sort(i)\n duration = round(time.time() - start, 6)\n\n results.append(Result('Bubble Sort', duration, sorted_numbers))\n\n # Insertion sort\n one_thousand = []\n for i in range(1000):\n one_thousand.append(numbers[:])\n\n start = time.time()\n for i in one_thousand:\n sorted_numbers = insertion_sort(i)\n duration = round(time.time() - start, 6)\n\n results.append(Result('Insertion Sort', duration, sorted_numbers))\n\n # Selection sort\n one_thousand = []\n for i in range(1000):\n one_thousand.append(numbers[:])\n\n start = time.time()\n for i in one_thousand:\n sorted_numbers = selection_sort(i)\n duration = round(time.time() - start, 6)\n results.append(Result('Selection Sort', duration, sorted_numbers))\n\n # Quick sort\n one_thousand = []\n for i in range(1000):\n one_thousand.append(numbers[:])\n\n start = time.time()\n for i in one_thousand:\n quick_sort(i, 0, len(i) - 1)\n duration = round(time.time() - start, 6)\n results.append(Result('Quick Sort', duration, i))\n\n fastest = determine_fastest(results)\n calculate_relative(results, fastest)\n\n results.sort(key=lambda x: x.relative)\n print_results(list_name, results)\n\n\n### Main runner ###\nif __name__ == '__main__':\n main()\n","sub_path":"sortanalytics/main_api.py","file_name":"main_api.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"56036530","text":"\"\"\"\nFact Checking Dataset Caching Script\n\nRun this script to re-produce caching the CalibraGPT/Fact_Checking dataset\nOriginal sources cited in the project's README\n\nExample usage:\npython cache_fact_completion_dataset.py\n\"\"\"\n\nimport os\nimport json\nimport pandas as pd\nimport numpy as np\nimport copy\nfrom argparse import ArgumentParser\nfrom datasets import load_dataset\nfrom huggingface_hub import login\nfrom dotenv import load_dotenv\n\n\ndef main(args):\n print(\"Caching the fact_completion dataset...\")\n\n # Load calinet data\n with open(\n \"../../data/calinet_data_original/probing-data-trex-500each.json\", \"r\"\n ) as f:\n data_calinet = json.load(f)\n starter_df = pd.DataFrame(list(data_calinet[\"data\"]))\n\n # all of these have to do with fact id 1\n # the sentences are formed in this format...\n # the start of a factual sentence, involving the subject\n # and then two possibilities: one true and one false?\n # storing these, then, we should do something like\n # sentence stem | correct | incorrect\n # and we can strip out the parts\n # to keep it model agnostic\n starter_df[\"sentences\"][0][0]\n\n # create containers to hold our clean data\n sentence_stems = []\n correct = []\n incorrect = []\n fact_ids = []\n relations = []\n subjects = []\n objects = []\n for index, row in starter_df.iterrows():\n sentence_list = row[\"sentences\"]\n for entry in sentence_list:\n # minor cleanup\n cleaned_stem = entry[0].replace(\"\", \"[BLANK]\").strip()\n cleaned_correct = (\n entry[1].replace(\"\", \"\").replace(\"\", \"\").strip()\n )\n cleaned_incorrect = (\n entry[2].replace(\"\", \"\").replace(\"\", \"\").strip()\n )\n\n # grab sub<->obj\n subjects_and_objects = pd.json_normalize(row[\"triplet\"])\n subjects.append(subjects_and_objects.sub_label.values[0])\n objects.append(subjects_and_objects.obj_label.values[0])\n\n # commit\n sentence_stems.append(cleaned_stem)\n correct.append(cleaned_correct)\n incorrect.append(cleaned_incorrect)\n fact_ids.append(row[\"fact_id\"])\n relations.append(row[\"relation\"])\n\n # sanity check\n assert (\n len(sentence_stems)\n == len(correct)\n == len(incorrect)\n == len(fact_ids)\n == len(relations)\n == len(subjects)\n == len(objects)\n )\n\n # merge into big df\n trex_df = pd.DataFrame(\n {\n \"fact_id\": fact_ids,\n \"relation\": relations,\n \"subject\": subjects,\n \"object\": objects,\n \"stem\": sentence_stems,\n \"true\": correct,\n \"false\": incorrect,\n }\n )\n\n # how many stems end in [BLANK]? -> 50451, or about 1/3.\n c = 0\n for stem in trex_df[\"stem\"]:\n if stem.endswith(\"[BLANK].\"):\n c += 1\n\n print(\n f\"\\t- Calinet dataset: There are {c} valid stem/fact pairs in the source data.\"\n )\n print(\n f\"\\t- Calinet dataset: There are {len(trex_df)} valid counterfacts\"\n \" in the source data.\"\n )\n\n def check_for_causal_compatibility(stem):\n return stem.endswith(\"[BLANK].\")\n\n def trim_stem(stem):\n if stem.endswith(\"[BLANK].\"):\n return stem[0 : len(stem) - 9]\n\n trex_causal_df = trex_df[\n trex_df.apply(lambda x: check_for_causal_compatibility(x.stem), axis=1)\n ]\n trex_causal_df = trex_causal_df.copy()\n trimmed_stems = trex_causal_df.apply(lambda x: trim_stem(x.stem), axis=1)\n trex_causal_df[\"stem\"] = list(trimmed_stems)\n\n unique_trex = (\n len(trex_causal_df[\"fact_id\"].unique()) / len(trex_causal_df[\"fact_id\"]) * 100\n )\n print(\n f\"\\t- Calinet dataset: Only about {np.round(unique_trex, decimals=1)}\"\n \"% of the stem/fact pairs are unique (many are paraphrased).\"\n )\n\n # before sampling, attach arbitrary counter ID, to then track who gets removed\n trex_causal_df[\"calibra_id\"] = range(50451)\n trex_causal_subset = (\n trex_causal_df.groupby(\"fact_id\")\n .apply(lambda x: x.sample(1, random_state=42))\n .reset_index(drop=True)\n )\n assert trex_causal_subset.shape[0] == len(trex_causal_df[\"fact_id\"].unique())\n trex_causal_subset.head()\n\n trex_causal_subset.tail()\n\n removed_ids = {}\n removed_counterfacts = {}\n for c_id in trex_causal_df[\"calibra_id\"]:\n if c_id not in trex_causal_subset[\"calibra_id\"].values:\n fact_id = trex_causal_df[trex_causal_df[\"calibra_id\"] == c_id][\n \"fact_id\"\n ].values[0]\n counterfact = trex_causal_df[trex_causal_df[\"calibra_id\"] == c_id][\n \"false\"\n ].values[0]\n removed_ids[str(c_id)] = int(fact_id)\n if str(fact_id) in removed_counterfacts:\n removed_counterfacts[str(fact_id)].append(counterfact)\n else:\n removed_counterfacts[str(fact_id)] = [counterfact]\n\n # did we remove as many rows as eq to the difference between the full calinet\n # dataset row number and the unique count?\n assert len(removed_ids) == trex_causal_df.shape[0] - len(\n trex_causal_df[\"fact_id\"].unique()\n )\n # drop extraneous calibra_id column\n trex_causal_subset.drop([\"calibra_id\"], axis=1, inplace=True)\n # there are some fact_id's that only have 1 row\n # since we did pull stuff out based on our left to right requirement\n full_falses = {}\n for k, v in removed_counterfacts.items():\n subset_false = trex_causal_subset[\n trex_causal_subset[\"fact_id\"] == int(k)\n ].false.values[0]\n full_falses[k] = v\n full_falses[k].append(subset_false)\n\n def replace_false_column(fact_id, false_val, full_false_dict=full_falses):\n if str(fact_id) in full_false_dict:\n return full_false_dict[str(fact_id)]\n else:\n return [false_val]\n\n replaced_falses = list(\n trex_causal_subset.apply(\n lambda x: replace_false_column(x.fact_id, x.false), axis=1\n )\n )\n\n trex_causal_subset[\"false\"] = replaced_falses\n\n trex_causal_subset.head()\n trex_causal_subset.tail()\n data_calinet_input_information = {}\n trex_list = trex_causal_subset.to_dict(\"records\")\n for i, entry in enumerate(trex_list):\n data_calinet_input_information[i] = trex_list[i]\n num_pairs = 0\n for x, y in data_calinet_input_information.items():\n data_calinet_input_information[x] = y\n data_calinet_input_information[x][\"false\"] = list(set(y[\"false\"]))\n\n num_pairs += len(data_calinet_input_information[x][\"false\"])\n\n print(\n f\"\\t- Calinet dataset: There are {len(data_calinet_input_information)}\"\n \" stem/fact pairs left after removing paraphrases.\"\n )\n print(\n f\"\\t- Calinet dataset: There are {num_pairs} counterfacts left after\"\n \" removing paraphrases.\"\n )\n\n # Load in ROME counterfact data\n with open(\"../../data/rome_data_original/counterfact.json\", \"r\") as f:\n data_rome = json.load(f)\n\n print(\n f\"\\n\\t- Rome dataset: There are {len(data_rome)} valid stem/fact pairs\"\n \" in the source data.\"\n )\n print(\n f\"\\t- Rome dataset: There are {len(data_rome)} valid counterfacts in\"\n \" the source data.\"\n )\n data_rome_input_information = {}\n\n for i in range(len(data_rome)):\n stem = data_rome[i][\"requested_rewrite\"][\"prompt\"].replace(\n \"{}\", data_rome[i][\"requested_rewrite\"][\"subject\"]\n )\n\n data_rome_input_information[str(i)] = {\n \"stem\": stem,\n \"true\": data_rome[i][\"requested_rewrite\"][\"target_true\"][\"str\"],\n \"false\": [data_rome[i][\"requested_rewrite\"][\"target_new\"][\"str\"]],\n \"case_id\": data_rome[i][\"case_id\"],\n }\n # Combine the two datasets\n # start from a clean var\n\n data_rome = copy.deepcopy(data_rome_input_information)\n data_calinet = copy.deepcopy(data_calinet_input_information)\n mixed_itr = 0\n mixed_df = {}\n\n for x, y in data_calinet.items():\n y[\"dataset_original\"] = \"calinet_input_information\"\n mixed_df[str(mixed_itr)] = y\n\n mixed_itr += 1\n\n for x, y in data_rome.items():\n y[\"dataset_original\"] = \"rome_counterfact_input_information\"\n mixed_df[str(mixed_itr)] = y\n mixed_itr += 1\n\n # Convert dicts to pandas, then optionally upload to HuggingFace\n pairs_list = []\n for x, y in mixed_df.items():\n pairs = y[\"stem\"] + \" \" + y[\"true\"]\n pairs_list.append(pairs)\n\n print(\n f\"\\n\\t- Combined dataset: There are {len(pairs_list)} stem/fact\"\n \" pairs after combining data.\"\n )\n\n pairs_list = []\n for x, y in mixed_df.items():\n for itr in range(len(y[\"false\"])):\n pairs = y[\"stem\"] + \" \" + y[\"true\"] + \" \" + y[\"false\"][itr]\n pairs_list.append(pairs)\n\n print(\n f\"\\t- Combined dataset: There are {len(pairs_list)} counterfacts\"\n \" after combining data.\"\n )\n\n # update mixed_df to have all info for rome then write that out.\n mixed_df = pd.DataFrame.from_dict(mixed_df).T\n # get rome info to look at:\n with open(\"../../data/rome_data_original/counterfact.json\", \"r\") as f:\n data_rome_original = json.load(f)\n rome_df = pd.DataFrame.from_dict(data_rome_original)\n\n # 3/20 data frame cleanup: adding subject/object columns\n rome_subjects = {}\n rome_objects = {}\n rome_relations = {}\n\n for i, rewrite in enumerate(rome_df[\"requested_rewrite\"]):\n rome_subjects[i] = rewrite[\"subject\"]\n rome_objects[i] = rewrite[\"target_true\"][\"str\"]\n rome_relations[i] = rewrite[\"relation_id\"]\n\n assert (\n len(rome_subjects)\n == len(rome_objects)\n == len(rome_relations)\n == rome_df.shape[0]\n )\n subjects = []\n objects = []\n ids = []\n relations = []\n\n for row in mixed_df.iterrows():\n if row[1][\"dataset_original\"] == \"calinet_input_information\":\n subjects.append(row[1][\"subject\"])\n objects.append(row[1][\"object\"])\n relations.append(row[1][\"relation\"])\n ids.append(\"calinet_\" + str(row[1][\"fact_id\"]))\n if row[1][\"dataset_original\"] == \"rome_counterfact_input_information\":\n # get case id\n case_id = row[1][\"case_id\"]\n\n # get subject\n subjects.append(rome_subjects[case_id])\n # get object\n objects.append(rome_objects[case_id])\n # get relation\n relations.append(rome_relations[case_id])\n ids.append(\"rome_\" + str(case_id))\n\n assert len(subjects) == len(objects) == len(ids) == len(relations)\n mixed_df[\"subject\"] = subjects\n mixed_df[\"object\"] = objects\n mixed_df[\"relation\"] = relations\n mixed_df[\"dataset_id\"] = ids\n mixed_df.drop([\"fact_id\", \"case_id\", \"dataset_original\"], axis=1, inplace=True)\n assert not mixed_df.isnull().values.any()\n mixed_df.head()\n # re-arrange cols\n mixed_df = mixed_df[\n [\"dataset_id\", \"stem\", \"true\", \"false\", \"relation\", \"subject\", \"object\"]\n ]\n # write to file as .parquet\n mixed_df.to_parquet(\n \"../../data/ingested_data/en-fact-completion-3-20-23.parquet\",\n index=False,\n )\n\n # further cleanup based on an analysis of the top-100 most confident misses\n # delete erroneous entries in the dataset\n # (these were not exhaustively searched for, some\n # errors could still exist in the data)\n rows_to_delete = [\n \"rome_19765\",\n \"calinet_9087\",\n \"rome_9674\",\n \"rome_13669\",\n \"rome_17792\",\n \"calinet_469\",\n \"calinet_12945\",\n \"rome_17452\",\n \"rome_597\",\n \"calinet_7656\",\n \"rome_16474\",\n \"rome_6020\",\n \"rome_9479\",\n \"calinet_5834\",\n \"rome_9414\",\n \"rome_6487\",\n \"rome_10852\",\n \"rome_14709\",\n \"rome_4358\",\n \"rome_10342\",\n \"calinet_12839\",\n \"rome_19963\",\n \"rome_5757\",\n \"rome_3604\",\n \"rome_8710\",\n \"calinet_2551\",\n \"rome_20688\",\n \"rome_15441\",\n \"calinet_12842\",\n \"calinet_9348\",\n \"calinet_2516\",\n \"calinet_12777\",\n \"rome_13682\",\n \"calinet_29\",\n \"calinet_3198\",\n \"rome_10178\",\n \"rome_19495\",\n \"rome_9674\",\n \"rome_13028\",\n \"calinet_5452\",\n \"rome_19963\",\n \"calinet_2568\",\n \"calinet_5475\",\n \"calinet_9555\",\n \"rome_19788\",\n \"rome_12483\",\n \"rome_14334\",\n \"calinet_10778\",\n \"rome_612\",\n \"rome_8416\",\n \"calinet_5133\",\n \"calinet_5185\",\n \"rome_1525\",\n \"rome_5796\",\n \"rome_1359\",\n \"rome_15982\",\n \"rome_12882\",\n \"rome_796\",\n \"rome_7201\",\n \"rome_4998\",\n \"calinet_9032\",\n \"rome_15759\",\n \"rome_8513\",\n \"rome_9528\",\n \"rome_9653\",\n \"rome_13961\",\n \"rome_14778\",\n \"rome_2140\",\n \"rome_16482\",\n \"rome_4091\",\n \"rome_11399\",\n \"rome_19798\",\n \"calinet_8491\",\n \"calinet_8312\",\n \"calinet_8413\",\n \"rome_11510\",\n \"calinet_1609\",\n \"calinet_10514\",\n \"calinet_8022\",\n \"calinet_3508\",\n \"calinet_10716\",\n \"calinet_10294\",\n \"calinet_5256\",\n \"calinet_11265\",\n \"calinet_11400\",\n \"calinet_3307\",\n \"rome_14732\",\n \"rome_2374\",\n \"rome_7730\",\n \"calinet_10137\",\n \"calinet_10391\",\n \"calinet_3722\",\n \"calinet_3613\",\n \"calinet_3132\",\n \"calinet_10574\",\n \"calinet_3306\",\n \"calinet_7200\",\n \"calinet_8310\",\n \"calinet_3199\",\n \"calinet_10171\",\n \"calinet_9368\",\n \"calinet_5324\",\n \"calinet_470\",\n \"calinet_9347\",\n \"calinet_10393\",\n \"calinet_9445\",\n \"rome_10198\",\n \"calinet_5669\",\n \"rome_7352\",\n \"rome_1814\",\n \"calinet_5334\",\n \"rome_16980\",\n \"calinet_12130\",\n \"calinet_494\",\n \"calinet_1878\",\n \"calinet_3864\",\n \"rome_9081\",\n \"calinet_5849\",\n \"calinet_8111\",\n \"rome_8201\",\n \"calinet_4579\",\n \"calinet_10145\",\n \"calinet_1637\",\n \"calinet_5803\",\n \"rome_626\",\n \"calinet_9319\",\n \"calinet_5982\",\n \"calinet_6694\",\n \"calinet_6537\",\n \"calinet_5736\",\n \"calinet_1522\",\n \"calinet_5551\",\n \"calinet_10221\",\n \"calinet_3969\",\n \"calinet_6304\",\n \"calinet_3549\",\n \"calinet_1829\",\n \"calinet_3544\",\n \"calinet_8465\",\n \"calinet_6629\",\n \"calinet_12082\",\n \"calinet_1819\",\n \"rome_9477\",\n \"calinet_10184\",\n \"calinet_5905\",\n \"calinet_5671\",\n \"rome_15012\",\n \"rome_398\",\n \"calinet_12611\",\n \"calinet_609\",\n \"rome_3106\",\n \"rome_18739\",\n \"rome_3929\",\n \"calinet_4504\",\n \"calinet_2829\",\n \"calinet_2263\",\n \"calinet_6596\",\n \"calinet_7812\",\n \"calinet_12256\",\n \"calinet_5838\",\n \"calinet_1577\",\n \"calinet_1538\",\n \"rome_4716\",\n \"rome_7858\",\n \"calinet_12153\",\n \"calinet_8452\",\n \"rome_19436\",\n \"calinet_8223\",\n \"rome_9317\",\n \"calinet_9578\",\n \"calinet_1602\",\n \"calinet_3377\",\n \"calinet_7072\",\n \"calinet_8153\",\n \"calinet_2832\",\n \"calinet_7417\",\n \"calinet_7676\",\n \"calinet_10130\",\n \"calinet_8450\",\n \"calinet_7898\",\n \"calinet_9660\",\n \"calinet_10233\",\n \"rome_1131\",\n \"calinet_8450\",\n \"rome_18347\",\n \"rome_17012\",\n \"calinet_3302\",\n \"rome_2809\",\n \"calinet_5713\",\n \"rome_12017\",\n \"calinet_9441\",\n \"calinet_5750\",\n \"calinet_3636\",\n \"calinet_12289\",\n \"calinet_3556\",\n \"calinet_3589\",\n \"calinet_3523\",\n \"calinet_2807\",\n \"calinet_6282\",\n \"calinet_3605\",\n \"calinet_104\",\n \"calinet_447\",\n \"calinet_3947\",\n \"calinet_3966\",\n \"calinet_12194\",\n \"calinet_401\",\n \"rome_3244\",\n \"calinet_6969\",\n \"rome_5017\",\n \"calinet_2379\",\n \"calinet_2063\",\n \"calinet_2140\",\n \"calinet_9994\",\n \"calinet_2418\",\n \"calinet_2084\",\n \"calinet_1941\",\n \"rome_4233\",\n \"calinet_7183\",\n \"calinet_12628\",\n \"calinet_9160\",\n \"calinet_12789\",\n \"rome_1906\",\n \"calinet_137\",\n \"calinet_4516\",\n \"rome_19266\",\n \"rome_15136\",\n \"rome_15088\",\n \"calinet_5977\",\n \"calinet_3324\",\n \"calinet_8503\",\n ]\n\n # delete these rows\n for i in list(mixed_df.index):\n if mixed_df.loc[i].dataset_id in list(set(rows_to_delete)):\n # print(mixed_df.loc[i].dataset_id)\n mixed_df.drop(i, axis=0, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {len(set(rows_to_delete))}\"\n \" stem/fact pairs that were manually flagged as errors.\"\n )\n\n mixed_df.shape[0]\n\n # delete stems that end with \"a\" or \"an\"\n itr = 0\n for i in list(mixed_df.index):\n if (mixed_df.loc[i].stem[-2:] == \" a\") or (mixed_df.loc[i].stem[-3:] == \" an\"):\n itr += 1\n mixed_df.drop(i, axis=0, inplace=True)\n\n print(f'\\t- Combined dataset: Removed {itr} stem/fact pairs with \"a/an + _\".')\n mixed_df.reset_index(drop=True, inplace=True)\n\n # modify errors when sandwitched with correct data where possible\n # dictionary: dataset_id and new counterfact list, with the error removed\n rows_to_alter = {\n \"calinet_7809\": {\"false\": [\"Gaulish\", \"Georgian\"]},\n \"calinet_1917\": {\"false\": [\"theology\", \"free software\", \"accounting\"]},\n \"calinet_7790\": {\"false\": [\"Hebrew\", \"Swahili\"]},\n \"rome_11311\": {\"false\": [\"Russian\"], \"true\": \"French\", \"object\": \"French\"},\n \"rome_17917\": {\"false\": [\"French\"], \"true\": \"Russian\", \"object\": \"Russian\"},\n \"calinet_7612\": {\"false\": [\"Phir Subah Hogi\"]},\n \"calinet_12317\": {\n \"false\": [\"Emperor\", \"Prime Minister\"],\n \"true\": \"President\",\n \"object\": \"President\",\n },\n \"rome_5908\": {\"false\": [\"violin\"], \"true\": \"guitar\", \"object\": \"guitar\"},\n \"rome_21907\": {\"false\": [\"French\"], \"true\": \"English\", \"object\": \"English\"},\n \"calinet_11761\": {\"false\": [\"Apple\"]},\n \"calinet_2821\": {\"stem\": \"The Italian capital is\", \"subject\": \"capital\"},\n \"calinet_10786\": {\n \"false\": [\"America\", \"Germany\"],\n \"true\": \"Russia\",\n \"object\": \"Russia\",\n },\n \"calinet_12059\": {\n \"false\": [\"President\", \"Supreme Court Justice\"],\n },\n \"calinet_143\": {\n \"false\": [\"California\", \"Canada\"],\n },\n \"calinet_5721\": {\n \"stem\": \"New Delhi is the capital city of\",\n \"true\": \"India\",\n \"false\": [\"Pakistan\"],\n \"subject\": \"New Delhi\",\n },\n \"calinet_12403\": {\n \"true\": \"Prime Minister\",\n \"false\": [\"President\", \"Governor\"],\n \"object\": \"Prime Minister\",\n },\n \"rome_18212\": {\n \"stem\": \"The Australian Open is held in\",\n \"false\": [\"Sydney\"],\n \"subject\": \"The Australian Open\",\n },\n \"rome_19787\": {\n \"stem\": \"The 1993 Bombay bombings took place in\",\n \"false\": [\"New Delhi\"],\n },\n \"calinet_6228\": {\n \"stem\": \"Marvin Gaye passed way in\",\n \"true\": \"Los Angeles\",\n \"false\": [\"Houston\"],\n \"object\": \"Los Angeles\",\n },\n \"calinet_681\": {\n \"true\": \"Athens\",\n \"false\": [\"Sparta\", \"Corinth\"],\n \"object\": \"Athens\",\n },\n \"calinet_7198\": {\n \"true\": \"Molsheim, France\",\n \"object\": \"Molsheim, France\",\n \"false\": [\"Maranello, Italy\"],\n },\n \"rome_17865\": {\n \"stem\": \"What does Wanda Sykes do? They write\",\n \"subject\": \"Wanda Sykes\",\n \"false\": [\"literature\"],\n },\n \"calinet_3768\": {\n \"stem\": \"Pearl Jam was formed in\",\n \"true\": \"Seattle\",\n \"object\": \"Seattle\",\n \"false\": [\"Los Angeles\"],\n },\n \"calinet_9216\": {\n \"stem\": \"Rolling Stone Magazine is written in\",\n \"subject\": \"Rolling Stone Magazine\",\n \"false\": [\"Spanish\"],\n },\n \"calinet_5824\": {\n \"stem\": \"Hungary, which has the capital\",\n \"object\": \"Hungary\",\n \"false\": [\"Vienna\"],\n },\n \"calinet_12363\": {\n \"false\": [\"Senator\"],\n \"true\": \"President\",\n \"object\": \"President\",\n },\n \"calinet_2180\": {\n \"false\": [\"Munich, Denver, Boston\"],\n },\n \"calinet_2742\": {\n \"true\": \"Munich\",\n \"false\": [\"Prague\"],\n \"object\": \"Munich\",\n },\n \"calinet_2820\": {\n \"false\": [\"Kampala\"],\n },\n \"calinet_8922\": {\n \"false\": [\"Honda\"],\n },\n \"calinet_5926\": {\n \"false\": [\"Zhejiang Province\"],\n },\n \"calinet_10906\": {\n \"false\": [\"Canada\"],\n },\n \"calinet_10852\": {\"false\": [\"Canada\"], \"true\": \"America\", \"object\": \"America\"},\n \"calinet_5749\": {\n \"true\": \"Lebanon\",\n \"false\": [\"Syria\"],\n \"object\": \"Lebanon\",\n },\n \"calinet_2811\": {\n \"stem\": \"The capital city of America is\",\n \"subject\": \"America\",\n },\n \"calinet_10312\": {\n \"stem\": \"America is affiliated with\",\n \"false\": [\"Warsaw Pact\"],\n \"subject\": \"America\",\n },\n \"calinet_5576\": {\n \"false\": [\"Jamaica\"],\n },\n \"calinet_6356\": {\n \"false\": [\"Philadelphia\"],\n },\n \"calinet_156\": {\n \"false\": [\"Uganda\"],\n },\n \"calinet_8171\": {\n \"false\": [\"Taylor Swift\"],\n },\n \"calinet_7004\": {\n \"false\": [\"Seattle, Washington\"],\n },\n \"calinet_5516\": {\n \"false\": [\"Norway\"],\n },\n \"calinet_8388\": {\n \"false\": [\"hip hop\"],\n },\n \"rome_9037\": {\n \"stem\": \"How I Met Your Mother is a\",\n },\n \"calinet_12121\": {\n \"stem\": \"Lyndon Johnson, who has the position of\",\n \"false\": [\"Vice President\", \"UN Secretary-General\"],\n },\n \"calinet_6983\": {\n \"false\": [\"New York City, New York\"],\n },\n \"calinet_8410\": {\"stem\": \"Metal musicians\", \"false\": [\"Coldplay\"]},\n \"rome_15790\": {\n \"true\": \"astronomy\",\n \"object\": \"astronomy\",\n \"false\": [\"literature\"],\n },\n \"calinet_1797\": {\n \"false\": [\"anthropology\"],\n },\n \"rome_17056\": {\n \"false\": [\"literature\"],\n },\n \"calinet_3106\": {\n \"false\": [\"Pakistan\"],\n },\n \"calinet_5819\": {\n \"false\": [\"Vancouver\", \"Quebec City\", \"Toronto\"],\n },\n \"calinet_6739\": {\n \"false\": [\"London\"],\n \"true\": \"Cambridge\",\n \"object\": \"Cambridge\",\n },\n \"calinet_2640\": {\"false\": [\"Kyoto\"], \"true\": \"Tokyo\", \"object\": \"Tokyo\"},\n \"rome_11966\": {\n \"false\": [\"Budapest\"],\n \"stem\": \"Austria, which has the capital\",\n \"subject\": \"Austria\",\n },\n \"calinet_7356\": {\n \"false\": [\"Rome\"],\n },\n \"calinet_209\": {\n \"false\": [\"Thailand\"],\n },\n \"calinet_42\": {\n \"false\": [\"Texas\"],\n },\n \"calinet_7125\": {\n \"false\": [\"Dallas\", \"San Francisco\", \"Chicago\"],\n },\n \"rome_9881\": {\n \"true\": \"folk\",\n \"object\": \"folk\",\n },\n \"rome_9646\": {\n \"true\": \"Basel\",\n \"object\": \"Basel\",\n },\n }\n\n for key, dictionary in rows_to_alter.items():\n for column, edit in dictionary.items():\n row_ind = mixed_df[mixed_df.dataset_id == key].false.index[0]\n mixed_df.loc[row_ind, column] = edit\n\n # fix small syntax and grammatical errors, remove templates scheduled to be dropped\n for i in range(len(mixed_df)):\n # bespoke syntax fixes\n if \"shares border with\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"shares border with\", \"shares a border with\"\n )\n elif \"shares the border with\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"shares the border with\", \"shares a border with\"\n )\n elif \"borders with\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"borders with\", \"shares a border with\"\n )\n if \"premiered\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"premiered\", \"originally aired\"\n )\n if \"The Smashing Pumpkins, who plays\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"The Smashing Pumpkins, who plays\", \"The Smashing Pumpkins, who play\"\n )\n if \"is to debut on\" in mixed_df.loc[i].stem:\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem.replace(\n \"is to debut on\", \"originally aired on\"\n )\n if mixed_df.loc[i].stem.split(\" \")[-1] == \"debuted\":\n mixed_df.loc[i, \"stem\"] = mixed_df.loc[i].stem + \" on\"\n\n # remove rows where the true answer is in the stem\n itr_true_in_stem = 0\n for i in range(len(mixed_df)):\n delete_bool = False\n for word in mixed_df.loc[i].true.lower().split(\" \"):\n if mixed_df.loc[i].stem.lower().count(word) > 0:\n delete_bool = True\n if delete_bool:\n itr_true_in_stem += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_true_in_stem} stem/fact pairs\"\n \" where the fact is explicitly stated in the stem\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove sister city related relations\n itr_sister_city = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].relation == \"P190\":\n itr_sister_city += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_sister_city} stem/fact pairs\"\n \" that were relation P190 (sister city)\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove religion related rows\n itr_religion = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].relation == \"P140\":\n itr_religion += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_religion} stem/fact pairs\"\n \" that were relation P140 (religion)\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove \"tie diplomatic ties\" items\n itr_diplomatic = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].relation == \"P530\":\n itr_diplomatic += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_diplomatic} stem/fact pairs\"\n \" that were relation P530 (diplomatic ties)\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove \"citizen of\" items\n itr_citizen = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].relation == \"P27\":\n itr_citizen += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_citizen} stem/fact pairs that\"\n \" were relation P27 (citizen of)\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove \"affiliated with\" items\n itr_affiliated = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].relation == \"P463\":\n itr_affiliated += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_affiliated} stem/fact pairs\"\n \" that were relation P463 (affiliated with)\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove soccer/football comparisons\n itr_football_soccer = 0\n for i in range(len(mixed_df)):\n if (mixed_df.loc[i].true == \"soccer\") or (mixed_df.loc[i].true == \"football\"):\n if (\"soccer\" in mixed_df.loc[i].false) or (\n \"football\" in mixed_df.loc[i].false\n ):\n if len(mixed_df.loc[i].false) == 1:\n itr_football_soccer += 1\n mixed_df.drop(index=i, inplace=True)\n else:\n if \"soccer\" in mixed_df.loc[i].false:\n false_list = copy.deepcopy(mixed_df.loc[i].false)\n false_list.remove(\"soccer\")\n mixed_df.loc[i, \"false\"] = false_list\n if \"football\" in mixed_df.loc[i].false:\n false_list = copy.deepcopy(mixed_df.loc[i].false)\n false_list.remove(\"football\")\n mixed_df.loc[i, \"false\"] = false_list\n print(\n f\"\\t- Combined dataset: Removed {itr_football_soccer} stem/fact pairs\"\n \" that compared football with soccer\"\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove rows with \"expired at\"\n itr_expired = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].stem.lower().count(\"expired at\") > 0:\n itr_expired += 1\n mixed_df.drop(index=i, inplace=True)\n\n print(\n f\"\\t- Combined dataset: Removed {itr_expired} stem/fact pairs with\"\n ' \"expired at\" wording'\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove stems / true / false elements with \"-language\" in them\n itr_dash_language = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].true.lower().count(\"-language\") > 0:\n itr_dash_language += 1\n mixed_df.drop(index=i, inplace=True)\n elif mixed_df.loc[i].stem.lower().count(\"-language\") > 0:\n itr_dash_language += 1\n mixed_df.drop(index=i, inplace=True)\n else:\n false_list = copy.deepcopy(mixed_df.loc[i].false)\n for false in mixed_df.loc[i].false:\n if false.lower().count(\"-language\") > 0:\n false_list.remove(false)\n if len(false_list) > 0:\n mixed_df.loc[i, \"false\"] = false_list\n else:\n itr_dash_language += 1\n mixed_df.drop(index=i, inplace=True)\n print(\n f\"\\t- Combined dataset: Removed {itr_dash_language} stem/fact pairs\"\n ' with \"-language\" wording'\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # remove true / false elements that start with \"the\"\n itr_the = 0\n for i in range(len(mixed_df)):\n if mixed_df.loc[i].true.lower().split(\" \")[0] == \"the\":\n itr_the += 1\n mixed_df.drop(index=i, inplace=True)\n else:\n false_list = copy.deepcopy(mixed_df.loc[i].false)\n for false in mixed_df.loc[i].false:\n if false.lower().split(\" \")[0] == \"the\":\n false_list.remove(false)\n if len(false_list) > 0:\n mixed_df.loc[i, \"false\"] = false_list\n else:\n itr_the += 1\n mixed_df.drop(index=i, inplace=True)\n print(\n f\"\\t- Combined dataset: Removed {itr_the} stem/fact pairs with\"\n ' facts/counterfacts starting with \"the\"'\n )\n mixed_df.reset_index(drop=True, inplace=True)\n\n # find any duplicates resulting from above fixes\n # start with [stem + fact] pairs\n pairs_list = []\n pairs_list_duplicated = []\n itrs_duplicated = []\n for i in range(len(mixed_df)):\n pairs = (mixed_df.loc[i].stem, mixed_df.loc[i].true)\n if pairs in pairs_list:\n pairs_list_duplicated.append(pairs)\n itrs_duplicated.append(i)\n pairs_list.append(pairs)\n\n print(\n f\"\\t- Combined dataset: Removed {len(pairs_list) - len(set(pairs_list))}\"\n \" stem/fact pair duplicates.\"\n )\n\n # repair any duplicates resulting from above fixes\n pairs_list_collect = []\n for i in range(len(mixed_df)):\n pairs = (mixed_df.loc[i].stem, mixed_df.loc[i].true)\n if pairs in pairs_list_duplicated:\n pairs_list_collect.append(\n (mixed_df.loc[i].stem, mixed_df.loc[i].true, mixed_df.loc[i].false)\n )\n new_counterfacts = {}\n for element in pairs_list_collect:\n try:\n new_counterfacts[element[0] + \" \" + element[1]].extend(element[2])\n except KeyError:\n new_counterfacts[element[0] + \" \" + element[1]] = element[2]\n new_counterfacts_2 = {}\n for x, y in new_counterfacts.items():\n new_counterfacts_2[x] = list(set(y))\n for i in range(len(mixed_df)):\n key_item = mixed_df.loc[i].stem + \" \" + mixed_df.loc[i].true\n if key_item in list(new_counterfacts_2.keys()):\n mixed_df.loc[i, \"false\"] = new_counterfacts_2[key_item]\n mixed_df.drop_duplicates(subset=[\"stem\", \"true\"], inplace=True)\n mixed_df.reset_index(drop=True, inplace=True)\n\n # check duplicates were removed correctly\n pairs_list = []\n for i in range(len(mixed_df)):\n pairs = (mixed_df.loc[i].stem, mixed_df.loc[i].true)\n pairs_list.append(pairs)\n\n # shuffle the df's rows (without replacement)\n mixed_df = mixed_df.sample(\n frac=1, replace=False, random_state=44, ignore_index=True\n )\n\n # grab a subsest to include at the head, for sharing purposes\n good_subset = [\n \"rome_21844\",\n \"rome_9500\",\n \"rome_9881\",\n \"rome_11754\",\n \"calinet_8922\",\n \"rome_9037\",\n \"calinet_2820\",\n \"rome_10452\",\n \"rome_5025\",\n \"rome_15553\",\n \"rome_13484\",\n \"rome_957\",\n \"rome_14462\",\n \"rome_20584\",\n \"rome_11479\",\n \"calinet_5926\",\n \"rome_1397\",\n \"calinet_12363\",\n \"rome_21333\",\n \"rome_8738\",\n \"calinet_5824\",\n \"rome_8783\",\n \"calinet_12059\",\n \"calinet_4311\",\n \"calinet_143\",\n \"rome_3074\",\n \"rome_20293\",\n \"calinet_12403\",\n \"rome_1437\",\n \"calinet_4036\",\n \"rome_12802\",\n \"rome_15752\",\n \"rome_19787\",\n \"calinet_6228\",\n \"calinet_2742\",\n \"rome_15619\",\n \"calinet_681\",\n \"calinet_7198\",\n \"rome_17865\",\n \"calinet_3768\",\n \"calinet_9216\",\n \"calinet_12590\",\n \"calinet_5749\",\n \"calinet_10312\",\n \"calinet_6356\",\n \"calinet_5576\",\n \"rome_18369\",\n \"calinet_156\",\n \"rome_5419\",\n \"calinet_8171\",\n \"rome_17929\",\n \"calinet_7004\",\n \"calinet_5516\",\n \"rome_14610\",\n \"calinet_8388\",\n \"rome_20965\",\n \"rome_10068\",\n \"rome_11693\",\n \"calinet_5684\",\n \"rome_3161\",\n \"calinet_12121\",\n \"calinet_6266\",\n \"rome_16867\",\n \"calinet_8410\",\n \"rome_4790\",\n \"rome_15892\",\n \"calinet_10027\",\n \"rome_3586\",\n \"rome_259\",\n \"rome_10548\",\n \"rome_10145\",\n \"rome_15334\",\n \"calinet_4853\",\n \"calinet_7490\",\n \"calinet_7109\",\n \"rome_21525\",\n \"rome_2650\",\n \"rome_4897\",\n \"calinet_1797\",\n \"rome_17056\",\n \"rome_1633\",\n \"rome_6657\",\n \"rome_21008\",\n \"calinet_5819\",\n \"calinet_6739\",\n \"rome_17595\",\n \"rome_20749\",\n \"rome_7651\",\n \"calinet_7356\",\n \"calinet_209\",\n \"rome_1077\",\n \"rome_21420\",\n \"calinet_42\",\n \"rome_15949\",\n \"rome_9753\",\n \"calinet_7125\",\n \"rome_20823\",\n \"rome_6678\",\n \"rome_9989\",\n \"rome_997\",\n \"rome_9925\",\n \"rome_991\",\n \"rome_9836\",\n \"rome_9740\",\n \"rome_9717\",\n \"rome_9707\",\n \"rome_9646\",\n \"rome_964\",\n \"rome_9628\",\n \"rome_9606\",\n ]\n good_subset.reverse()\n for dataset_id in good_subset:\n id = mixed_df[mixed_df.dataset_id == dataset_id].index\n mixed_df = pd.concat([mixed_df.loc[id], mixed_df])\n mixed_df.drop_duplicates(subset=[\"dataset_id\"], inplace=True)\n mixed_df.dropna(inplace=True)\n mixed_df.reset_index(drop=True, inplace=True)\n # make sure all counterfacts are sets\n pairs_list = []\n for i in range(len(mixed_df)):\n mixed_df.loc[i, \"false\"] = list(set(mixed_df.loc[i, \"false\"]))\n\n # find any duplicates remaining\n # there shouldn't be, after the set command above\n pairs_list = []\n for i in range(len(mixed_df)):\n pairs = (mixed_df.loc[i].stem, mixed_df.loc[i].true)\n pairs_list.append(pairs)\n print(\n f\"\\t- Combined dataset: There are {len(set(pairs_list))} unique stem/fact pairs\"\n ' remaining in the final \"CalibraGPT/Fact_Checking\" dataset.'\n )\n assert len(set(pairs_list)) == len(mixed_df)\n\n pairs_list = []\n for i in range(len(mixed_df)):\n for item in mixed_df.loc[i].false:\n pairs = (mixed_df.loc[i].stem, mixed_df.loc[i].true, item)\n pairs_list.append(pairs)\n\n print(\n f\"\\t- Combined dataset: There are {len(set(pairs_list))} unique counterfacts\"\n ' remaining in the final \"CalibraGPT/Fact_Checking\" dataset.'\n )\n\n # convert lists to strings with
delimiters\n for i in range(len(mixed_df)):\n if len(mixed_df.loc[i].false) == 1:\n mixed_df.loc[i, \"false\"] = mixed_df.loc[i, \"false\"][0]\n else:\n string = mixed_df.loc[i, \"false\"][0]\n for element in mixed_df.loc[i, \"false\"][1:]:\n string += \"
\" + element\n mixed_df.loc[i, \"false\"] = string\n\n # capitalize the first letter\n for i in range(len(mixed_df)):\n stem = mixed_df.loc[i].stem[0].capitalize() + mixed_df.loc[i].stem[1:]\n mixed_df.loc[i, \"stem\"] = stem\n\n # write to file as .parquet\n mixed_df.to_parquet(\n \"../../data/ingested_data/en-fact-completion-3-21-23.parquet\",\n index=False,\n )\n\n # order by language popularity\n\n # Optionally upload final parquet to HuggingFace\n if args.hugging_face:\n data_files = {\n \"English\": \"../../data/ingested_data/en-fact-completion-3-21-23.parquet\",\n \"Spanish\": \"../../data/ingested_data/translated_versions/es-fact-completion-4-8-23.parquet\",\n \"French\": \"../../data/ingested_data/translated_versions/fr-fact-completion-4-5-23.parquet\",\n \"Russian\": \"../../data/ingested_data/translated_versions/ru-fact-completion-4-7-23.parquet\",\n \"Portuguese\": \"../../data/ingested_data/translated_versions/pt-fact-completion-4-8-23.parquet\",\n \"German\": \"../../data/ingested_data/translated_versions/de-fact-completion-4-7-23.parquet\",\n \"Italian\": \"../../data/ingested_data/translated_versions/it-fact-completion-4-9-23.parquet\",\n \"Ukrainian\": \"../../data/ingested_data/translated_versions/uk-fact-completion-4-9-23.parquet\",\n \"Polish\": \"../../data/ingested_data/translated_versions/pl-fact-completion-4-12-23.parquet\",\n \"Romanian\": \"../../data/ingested_data/translated_versions/ro-fact-completion-4-5-23.parquet\",\n \"Czech\": \"../../data/ingested_data/translated_versions/cs-fact-completion-4-10-23.parquet\",\n \"Bulgarian\": \"../../data/ingested_data/translated_versions/bg-fact-completion-4-10-23.parquet\",\n \"Swedish\": \"../../data/ingested_data/translated_versions/sv-fact-completion-4-10-23.parquet\",\n \"Serbian\": \"../../data/ingested_data/translated_versions/sr-fact-completion-4-12-23.parquet\",\n \"Hungarian\": \"../../data/ingested_data/translated_versions/hu-fact-completion-4-12-23.parquet\",\n \"Croatian\": \"../../data/ingested_data/translated_versions/hr-fact-completion-4-12-23.parquet\",\n \"Danish\": \"../../data/ingested_data/translated_versions/da-fact-completion-4-12-23.parquet\",\n \"Slovenian\": \"../../data/ingested_data/translated_versions/sl-fact-completion-4-12-23.parquet\",\n \"Dutch\": \"../../data/ingested_data/translated_versions/nl-fact-completion-4-12-23.parquet\",\n \"Catalan\": \"../../data/ingested_data/translated_versions/ca-fact-completion-4-12-23.parquet\",\n }\n dataset = load_dataset(\"parquet\", data_files=data_files)\n\n # This reads the environment variables inside .env\n load_dotenv()\n # Logs into HF hub\n login(os.getenv(\"HF_TOKEN\"))\n # push to hub\n dataset.push_to_hub(\"Polyglot-or-Not/Fact-Completion\")\n # test loading from hub\n load_dataset(\"Polyglot-or-Not/Fact-Completion\")\n\n return None\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\n \"--hugging_face\",\n type=bool,\n default=False,\n help=\"Whether or not to write to Hugging Face (access required)\",\n )\n\n args = parser.parse_args()\n main(args)\n","sub_path":"src/dataset_caching_scripts/cache_fact_completion_dataset.py","file_name":"cache_fact_completion_dataset.py","file_ext":"py","file_size_in_byte":41884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"217706647","text":"from django.test import TestCase\nfrom . import views\nfrom . import models\nfrom django.contrib.auth.models import User as us\nimport uuid\n\n# Create your tests here.\n\n\nclass Apartment(TestCase):\n def setUp(self) -> None:\n models.Apartment(address='amir', number_of_units=5,\n apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n\n def test_create_apartment(self):\n address = 'Tehran'\n number_of_units = 20\n res = views.create_apartment(address, number_of_units)\n self.assertTrue('Failed', res)\n\n def test_delete_apartment(self):\n apartment_id = '7y12312y2t'\n res = views.remove_apartment(apartment_id)\n self.assertTrue('Failed', res)\n\n def test_get_apartment(self):\n apartment_id = uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')\n res = views.get_apartment(apartment_id)\n self.assertEqual(True, res)\n\n\nclass User(TestCase):\n def setUp(self) -> None:\n a = us.objects.create_user(username = 'amirreza@yahoo.com', password='Amir1376')\n print('alex', a)\n def test_signup(self):\n email = 'test@example.com'\n password = 'tester'\n first_name = 'test'\n last_name = 'testian'\n phone_number = +989331532578\n unit = 4\n res = views.signupuser(email, password, first_name, last_name, phone_number, unit)\n self.assertTrue('Failed', res)\n\n def test_login(self):\n email = 'amirreza@yahoo.com'\n password = 'Amir1376'\n\n res = views.loginTest(email, password)\n print(res)\n self.assertEqual(True, res)\n\n def test_edit_user(self):\n user_id = 3\n email = 'test@example.com'\n password = 'tester'\n first_name = 'test'\n last_name = 'testian'\n phone_number = 989331532578\n unit = 4\n result = views.edit(user_id, email, password, first_name, last_name, phone_number, unit)\n self.assertTrue('Failed', result)\n\n def test_get_user(self):\n user_id = 'amirreza@yahoo.com'\n res = views.get_user(user_id)\n print(res)\n self.assertEqual(True, res)\n\n\nclass Unit(TestCase):\n def setUp(self) -> None:\n models.Apartment(address='nanaz', number_of_units=5, apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n models.Unit(unit_number=2, apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81'), phone=23154, number_of_people=5).save()\n\n def test_create_unit(self):\n unit_number = 2\n number_of_people = 3\n phone = 982166198045\n apartment = '7y12312y'\n res = views.create_unit(unit_number, number_of_people, phone, apartment)\n self.assertTrue('Failed', res)\n\n def test_edit_unit(self):\n unit_id = 1\n unit_number = 2\n number_of_people = 3\n phone = 982166198045\n res = views.edit_unit(unit_id, unit_number, number_of_people, phone)\n self.assertTrue('Failed', res)\n\n def test_get_unit(self):\n unit_id = 2\n res = views.get_unit(unit_id)\n self.assertEqual(True, res)\n\n\nclass Services(TestCase):\n def test_created_services(self):\n tracking_code = '7t5d6'\n unit = 3\n water = 20000\n gas = 30000\n electricity = 10000\n repairs = 20000\n cleaning = 30000\n res = views.create_services(tracking_code, unit, water, gas, electricity, repairs, cleaning)\n self.assertTrue('Failed', res)\n\n def test_edit_services(self):\n tracking_code = '7t5d6'\n unit = 3\n water = 20000\n gas = 25000\n electricity = 10000\n repairs = 52000\n cleaning = 36000\n res = views.edit_services(tracking_code, unit, water, gas, electricity, repairs, cleaning)\n self.assertTrue('Failed', res)\n\n def test_delete_services(self):\n tracking_code = '7t5d6'\n res = views.delete_services(tracking_code)\n self.assertTrue('Failed', res)\n\n def test_get_services(self):\n tracking_code = '7t5d6'\n res = views.get_services(tracking_code)\n self.assertTrue('Failed', res)\n\n\nclass Notification(TestCase):\n def setUp(self) -> None:\n models.Apartment(address='nanaz', number_of_units=5, apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n models.Notification(id=5, title='Amir', body='dwwd', apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n def test_create_notification(self):\n title = 'maintain'\n body = 'the elevator is crash'\n apartment = '3tu87123ol'\n res = views.create_notification(title, body, apartment)\n self.assertTrue('Failed', res)\n\n def test_edit_notification(self):\n notification_id = 23\n title = 'maintain'\n body = 'the elevator is crash'\n res = views.edit_notification(notification_id, title, body)\n self.assertTrue('Failed', res)\n\n def test_delete_notification(self):\n notification_id = 25\n res = views.delete_notification(notification_id)\n self.assertTrue('Failed', res)\n\n def test_get_notification(self):\n notification_id = 5\n res = views.get_notification(notification_id)\n self.assertEqual(True, res)\n\n\nclass Suggestion(TestCase):\n def test_send_suggest(self):\n title = 'bela bela'\n body = 'bela bela bela'\n res = views.send_suggest(title, body)\n self.assertTrue('Failed', res)\n\n def test_delete_suggest(self):\n suggestion_id = '123n24'\n res = views.delete_suggest(suggestion_id)\n self.assertTrue('Failed', res)\n\n def test_get_suggest(self):\n suggestion_id = 8\n res = views.get_suggest(suggestion_id)\n self.assertEqual(True, res)\n\n\nclass Vote(TestCase):\n def setUp(self) -> None:\n models.Vote(id=88, title='soal', body='body soal', date='2011-01-02', apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n models.Apartment(address='nanaz', number_of_units=5, apartment_id=uuid.UUID('c9686293-2ac1-4c96-b9a4-aa7002939d81')).save()\n\n def test_create_vote(self):\n title = 'fixing'\n body = 'What?'\n apartment_id = '4352433356'\n res = views.create_vote(title, body, apartment_id)\n self.assertTrue('Failed', res)\n\n def test_edit_vote(self):\n title = 'fixing'\n body = 'What?'\n res = views.edit_vote(title, body)\n self.assertTrue('Failed', res)\n\n def test_remove_vote(self):\n vote_id = 12\n res = views.remove_vote(vote_id)\n self.assertTrue('Failed', res)\n\n def test_get_vote(self):\n vote_id = 88\n res = views.get_vote(vote_id)\n self.assertEqual(True, res)\n","sub_path":"server/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"406808080","text":"from __future__ import print_function\n\nfrom .base import maybe_requirement_list\nfrom .fetcher import PyPIFetcher\nfrom .http import Crawler\nfrom .interpreter import PythonInterpreter\nfrom .obtainer import Obtainer\nfrom .platforms import Platform\nfrom .translator import Translator\n\nfrom pkg_resources import (\n Environment,\n WorkingSet,\n find_distributions,\n)\n\n\nclass ResolverEnvironment(Environment):\n def can_add(self, dist):\n return Platform.distribution_compatible(dist, python=self.python, platform=self.platform)\n\n\nclass ResolverBase(WorkingSet):\n def __init__(self, cache=None):\n self._cached_entries = set(find_distributions(cache)) if cache else set()\n self._entries = set()\n super(ResolverBase, self).__init__(entries=[])\n\n def make_installer(self, requirements, interpreter, platform):\n return None\n\n def resolve(self, requirements, interpreter=None, platform=None):\n requirements = maybe_requirement_list(requirements)\n interpreter = interpreter or PythonInterpreter.get()\n platform = platform or Platform.current()\n env = ResolverEnvironment([d.location for d in (self._entries | self._cached_entries)],\n python=interpreter.python,\n platform=platform)\n added = set()\n for dist in super(ResolverBase, self).resolve(requirements, env=env,\n installer=self.make_installer(requirements, interpreter, platform)):\n if dist not in self._entries:\n added.add(dist)\n self._entries.add(dist)\n return added\n\n def distributions(self):\n return self._entries\n\n\nclass Resolver(ResolverBase):\n def __init__(self, cache=None, crawler=None, fetchers=None, install_cache=None,\n conn_timeout=None):\n self._crawler = crawler or Crawler()\n self._fetchers = fetchers or [PyPIFetcher()]\n self._install_cache = install_cache\n self._conn_timeout = conn_timeout\n super(Resolver, self).__init__(cache=cache)\n\n def make_installer(self, reqs, interpreter, platform):\n obtainer = Obtainer(self._crawler, self._fetchers,\n Translator.default(self._install_cache, interpreter=interpreter, platform=platform,\n conn_timeout=self._conn_timeout))\n return obtainer.obtain\n","sub_path":"src/python/twitter/common/python/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"551578985","text":"import os, fnmatch, Versionamento\n\ndef find(pattern, path):\n\tresult = []\n\tfor root, dirs, files in os.walk(path):\n\t\tfor name in files:\n\t\t\tif fnmatch.fnmatch(name, pattern):\n\t\t\t\tresult.append(os.path.join(root, name))\n\treturn result\n\n\nprojetos = list()\nwith open(\"/home/gabriel/Documentos/ic2/analiseDosProjetosGerais/RQ1/selecaoDosProjetosAleatoriamente/projetosAleatorios.csv\") as entrada:\n for linha in entrada:\n linha=linha.replace(\"\\n\",\"\")\n projetos.append(linha.split(\",\"))\n\nprint(\"framework,projeto,caminho,minSdkVersion/springboot,targetSdkVersion\")\n\nfor projeto in projetos:\n tem_import = False\n if (projeto[0] == \"Android\"):\n gradles = find (\"build.gradle\", \"/home/gabriel/Documentos/ic2/analiseDosProjetosGerais/repositorios/\"+projeto[1])\n for gradle in gradles:\n arquivo_gradle = open(gradle).read()\n if(\"minSdkVersion\" in arquivo_gradle and \"targetSdkVersion\" in arquivo_gradle):\n tem_import = True\n\n posicao_inicial = arquivo_gradle.find(\"minSdkVersion\")\n \n minSdkVersion = arquivo_gradle[posicao_inicial:]\n\n posicao_inicial = minSdkVersion.find(\" \")\n\n minSdkVersion = minSdkVersion[posicao_inicial+1:]\n\n posicao_final = minSdkVersion.find(\"\\n\")\n \n minSdkVersion = minSdkVersion[:posicao_final]\n \n # target\n \n posicao_inicial = arquivo_gradle.find(\"targetSdkVersion\")\n \n targetSdkVersion = arquivo_gradle[posicao_inicial:]\n\n posicao_inicial = targetSdkVersion.find(\" \")\n\n targetSdkVersion = targetSdkVersion[posicao_inicial+1:]\n\n posicao_final = targetSdkVersion.find(\"\\n\")\n \n targetSdkVersion = targetSdkVersion[:posicao_final]\n\n print(projeto[0]+\",\"+projeto[1]+\",\"+gradle+\",\"+minSdkVersion+\",\"+targetSdkVersion)\n if(tem_import == False):\n print(projeto[0]+\",\"+projeto[1]+\",\"+\"Nao encontrado\")\n\n if(projeto[0]==\"Spring\"):\n poms = find(\"pom.xml\", \"/home/gabriel/Documentos/ic2/analiseDosProjetosGerais/repositorios/\"+projeto[1])\n for pom in poms:\n arquivo_pom = open(pom).read()\n if(\"org.springframework.boot\" in arquivo_pom):\n tem_import = True\n posicao = arquivo_pom.find(\"org.springframework.boot\")\n\n arquivo = arquivo_pom[posicao:]\n\n posicao= arquivo.find(\"version\")\n\n arquivo = arquivo[posicao:]\n\n posicao = arquivo.find(\">\")\n\n arquivo = arquivo[posicao+1:]\n\n posicao = arquivo.find(\"<\")\n\n versao = arquivo[:posicao]\n print(projeto[0]+\",\"+projeto[1]+\",\"+pom+\",\"+versao)\n if(tem_import == False):\n print(projeto[0]+\",\"+projeto[1]+\",\"+\"Nao encontrado\")","sub_path":"analiseDosProjetosGerais/RQ2/extraindoVersaoAtualDoFramework/pega_caminho_dos_pom_e_gradle.py","file_name":"pega_caminho_dos_pom_e_gradle.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"359459574","text":"\r\n\r\n\r\n\r\n\r\n\r\nlat_data_file = open(\"data/path.csv\")\r\ndata = lat_data_file.readlines()\r\n\r\nloc_json = open(\"path_data.json\", 'w')\r\nloc_json.write('{\\n\\t\"AllData\": \\n\\t[')\r\n\r\nfirst = True\r\n\r\nfor line in data[1:]:\r\n if not first:\r\n loc_json.write(\",\\n\")\r\n else:\r\n first = False\r\n line_data = line.strip().split(',')\r\n loc_json.write(\" \\n\\t\\t{\\n\\t\\t\\\"Data\\\": \\n\\t\\t[\\n\\t\\t\\t\")\r\n for i in range(len(line_data)):\r\n \tif line_data[i] != 'nan':\r\n \t\ttemp = line_data[i]\r\n \t\tif temp.endswith('.0'):\r\n \t\t\ttemp = temp[:-2]\r\n \t\tloc_json.write(\"\\\"\" + temp + \"\\\"\")\r\n \tif i < len(line_data) - 1 and line_data[i+1] != 'nan':\r\n \t\tloc_json.write(\", \")\r\n loc_json.write(\"\\n\\t\\t\\t]\\n\\t\\t}\")\r\n # print (line_data)\r\n # print (line_data)\r\n # loc_json.write(\" \\n\\t\\t{\\n\\t\\t\\\"Data\\\": \\n\\t\\t\\t[\\n\\t\\t\\t\\\"\" + line_data[1] + \"\\\", \\\"\" + line_data[2] +\r\n # \"\\\", \\\"\" + line_data[3] + \"\\\"\\n\\t\\t\\t]\\n\\t\\t}\")\r\n\r\nloc_json.write('\\n\\t]\\n}')\r\nloc_json.close()\r\n\r\nlat_data_file.close()\r\n","sub_path":"make_path_json.py","file_name":"make_path_json.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"297065736","text":"import numpy as np\nimport torch\n\nfrom collections import defaultdict\nfrom hyperopt import STATUS_OK\nfrom scvi.core.modules import SCANVAE\nfrom scvi.core.trainers import SemiSupervisedTrainer\nfrom sklearn.model_selection import train_test_split\nfrom scvi.data._anndata import get_from_registry\nfrom scvi import _CONSTANTS\n\n\ndef custom_objective_hyperopt(\n space, is_best_training=False, dataset=None, n_epochs=None\n):\n \"\"\"Custom objective function for advanced autotune tutorial.\"\"\"\n space = defaultdict(dict, space)\n model_tunable_kwargs = space[\"model_tunable_kwargs\"]\n trainer_tunable_kwargs = space[\"trainer_tunable_kwargs\"]\n train_func_tunable_kwargs = space[\"train_func_tunable_kwargs\"]\n\n trainer_specific_kwargs = {}\n model_specific_kwargs = {}\n train_func_specific_kwargs = {}\n trainer_specific_kwargs[\"use_cuda\"] = bool(torch.cuda.device_count())\n train_func_specific_kwargs[\"n_epochs\"] = n_epochs\n\n # add hardcoded parameters\n # disable scVI progbar\n trainer_specific_kwargs[\"silent\"] = True\n trainer_specific_kwargs[\"frequency\"] = 1\n\n # merge params with fixed param precedence\n model_tunable_kwargs.update(model_specific_kwargs)\n trainer_tunable_kwargs.update(trainer_specific_kwargs)\n train_func_tunable_kwargs.update(train_func_specific_kwargs)\n\n scanvi = SCANVAE(\n dataset.uns[\"_scvi\"][\"summary_stats\"][\"n_vars\"],\n dataset.uns[\"_scvi\"][\"summary_stats\"][\"n_batch\"],\n dataset.uns[\"_scvi\"][\"summary_stats\"][\"n_labels\"],\n **model_tunable_kwargs\n )\n trainer_scanvi = SemiSupervisedTrainer(scanvi, dataset, **trainer_tunable_kwargs)\n batch_indices = get_from_registry(dataset, _CONSTANTS.BATCH_KEY)\n trainer_scanvi.unlabelled_set = trainer_scanvi.create_scvi_dl(\n indices=(batch_indices == 1)\n )\n trainer_scanvi.unlabelled_set.to_monitor = [\"reconstruction_error\", \"accuracy\"]\n indices_labelled = batch_indices == 0\n\n if not is_best_training:\n # compute k-fold accuracy on a 20% validation set\n k = 5\n accuracies = np.zeros(k)\n indices_labelled = batch_indices == 0\n for i in range(k):\n indices_labelled_train, indices_labelled_val = train_test_split(\n indices_labelled.nonzero()[0], test_size=0.2\n )\n trainer_scanvi.labelled_set = trainer_scanvi.create_scvi_dl(\n indices=indices_labelled_train\n )\n trainer_scanvi.labelled_set.to_monitor = [\n \"reconstruction_error\",\n \"accuracy\",\n ]\n trainer_scanvi.validation_set = trainer_scanvi.create_scvi_dl(\n indices=indices_labelled_val\n )\n trainer_scanvi.validation_set.to_monitor = [\"accuracy\"]\n trainer_scanvi.train(**train_func_tunable_kwargs)\n accuracies[i] = trainer_scanvi.history[\"accuracy_unlabelled_set\"][-1]\n return {\"loss\": -accuracies.mean(), \"space\": space, \"status\": STATUS_OK}\n else:\n trainer_scanvi.labelled_set = trainer_scanvi.create_scvi_dl(\n indices=indices_labelled\n )\n trainer_scanvi.labelled_set.to_monitor = [\"reconstruction_error\", \"accuracy\"]\n trainer_scanvi.train(**train_func_tunable_kwargs)\n return trainer_scanvi\n","sub_path":"tests/notebooks/utils/autotune_advanced_notebook.py","file_name":"autotune_advanced_notebook.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"37308753","text":"from typing import Tuple\n\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef cast_rays(\n height: int,\n width: int,\n focal: float,\n pose: torch.Tensor,\n device: torch.device = \"cpu\",\n):\n ii, jj = torch.meshgrid(\n torch.arange(width, device=device),\n torch.arange(height, device=device),\n indexing=\"xy\",\n )\n directions = torch.stack(\n [\n (ii - width * 0.5) / focal,\n -(jj - height * 0.5) / focal,\n -torch.ones_like(ii),\n ],\n dim=-1,\n )\n directions = torch.sum(directions[..., None, :] * pose[:3, :3], dim=-1)\n origins = pose[:3, -1].expand(directions.shape)\n return origins, directions\n\n\ndef sample_points(\n origins: torch.Tensor,\n directions: torch.Tensor,\n z_near: float,\n z_far: float,\n num_samples: int,\n random: bool = True,\n device: torch.device = \"cpu\",\n):\n z = torch.linspace(z_near, z_far, num_samples, device=device)\n if random:\n noise = torch.rand(\n origins.shape[0], origins.shape[1], num_samples, device=device\n )\n z = z + noise * (z_far - z_near) / num_samples\n points = origins[..., None, :] + directions[..., None, :] * z[..., :, None]\n return points, z\n\n\ndef positional_encoding(\n x: torch.Tensor, encoding_size: int = 6, include_input: bool = True\n):\n encoding = [x] if include_input else []\n for i in range(encoding_size):\n for fn in [torch.sin, torch.cos]:\n encoding.append(fn((2**i) * x))\n return torch.cat(encoding, dim=-1)\n\n\ndef render_volume(\n samples: torch.Tensor, z: torch.Tensor\n) -> Tuple[torch.Tensor, torch.Tensor]:\n rgb = torch.sigmoid(samples[..., :3])\n sigma_a = F.relu(samples[..., 3])\n dist = z[..., 1:] - z[..., :-1]\n dist = torch.cat([dist, torch.full_like(z[..., :1], 1e10)], dim=-1)\n alpha = 1.0 - torch.exp(-sigma_a * dist)\n weights = alpha * torch.cumprod(1.0 - alpha + 1e-10, dim=-1)\n rgb = (weights[..., None] * rgb).sum(dim=-2)\n return rgb\n\n\nclass NeRF(nn.Module):\n def __init__(self, encoding_size: int = 6, hidden_channels: int = 256):\n super().__init__()\n in_channels = 3 + 3 * 2 * encoding_size\n self.fc1 = nn.Linear(in_channels, hidden_channels)\n self.fc2 = nn.Linear(hidden_channels, hidden_channels)\n self.fc3 = nn.Linear(hidden_channels, hidden_channels)\n self.fc4 = nn.Linear(hidden_channels, hidden_channels // 2)\n self.fc5 = nn.Linear(hidden_channels // 2, hidden_channels // 2)\n self.alpha = torch.nn.Linear(hidden_channels, 1)\n self.rgb = torch.nn.Linear(hidden_channels // 2, 3)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n alpha = self.alpha(x)\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n rgb = self.rgb(x)\n return torch.cat([rgb, alpha], dim=1)\n\n\nif __name__ == \"__main__\":\n device = \"cuda\"\n num_iters = 20000\n z_near = 2.0\n z_far = 6.0\n num_samples = 64 # Number of depth samples per ray\n chunk_size = 4096\n encoding_size = 10\n lr = 5e-3\n eval_freq = 100\n\n data = np.load(\"tinynerf.npz\")\n images = torch.from_numpy(data[\"images\"])\n poses = torch.from_numpy(data[\"poses\"])\n focal = torch.tensor(data[\"focal\"])\n\n height, width = images.shape[1:3]\n dataset_size = images.shape[0]\n\n model = NeRF(encoding_size).to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n\n pbar = tqdm(total=num_iters)\n for i in range(num_iters):\n choice = np.random.randint(100)\n image = images[choice].to(device)\n pose = poses[choice].to(device)\n origins, directions = cast_rays(height, width, focal, pose, device=device)\n points, z = sample_points(\n origins, directions, z_near, z_far, num_samples, device=device\n )\n points = points.reshape(-1, 3)\n encoding = positional_encoding(points, encoding_size)\n batches = torch.split(encoding, chunk_size)\n samples = [model(batch) for batch in batches]\n samples = torch.cat(samples, dim=0)\n samples = samples.reshape(height, width, num_samples, 4)\n rgb = render_volume(samples, z)\n\n optimizer.zero_grad()\n loss = F.mse_loss(rgb, image)\n loss.backward()\n optimizer.step()\n\n pbar.set_postfix(loss=loss.item())\n pbar.update()\n pbar.close()\n","sub_path":"nerf/nerf.py","file_name":"nerf.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619996915","text":"from collections import defaultdict as dd\nfrom random import randint, uniform\nfrom math import log\nfrom sys import exit\nfrom tqdm import tqdm\n\nNUM_TOPICS = 3\nFILEPATH = \"../files/data/wiki-en-documents.word\"\n\nALPHA = 0.01\nBETA = 0.01\n\ndef sample_one(probs):\n z = sum(probs)\n remaining = uniform(0, z)\n for i in range(len(probs)):\n remaining -= probs[i]\n if remaining <= 0:\n return i\n exit()\n\ndef add_counts(word, topic, doc_id, amounts, xcnts, ycnts):\n xcnts[f\"{topic}\"] += 1\n xcnts[f\"{word}|{topic}\"] += 1\n\n ycnts[f\"{doc_id}\"] += 1\n ycnts[f\"{topic}|{doc_id}\"] += 1\n\n\ndef initialize():\n xcorpus, ycorpus = [], []\n xcounts, ycounts = dd(int), dd(int)\n unique_words = set()\n\n for line in open(FILEPATH, \"r\", encoding=\"utf-8\"):\n doc_id = len(xcorpus)\n words = line.strip().split()\n topics = []\n\n for word in words:\n unique_words.add(word)\n topic = randint(0, NUM_TOPICS-1)\n topics.append(topic)\n\n add_counts(word, topic, doc_id, 1, xcounts, ycounts)\n\n xcorpus.append(words)\n ycorpus.append(topics)\n\n num_words = len(unique_words)\n return xcorpus, ycorpus, xcounts, ycounts, num_words\n\ndef sampling():\n xcorps, ycorps, xcnts, ycnts, num_words = initialize()\n ll = 0\n\n for i in tqdm(range(len(xcorps)), desc=\"sent\"):\n for j in range(len(xcorps[i])):\n x, y = xcorps[i][j], ycorps[i][j]\n add_counts(x, y, i, -1, xcnts, ycnts)\n\n probs = []\n for k in range(NUM_TOPICS):\n x_prob = (xcnts[f\"{x}|{k}\"] + ALPHA) / (xcnts[k] + ALPHA * num_words)\n y_prob = (ycnts[f\"{k}|{i}\"] + BETA) / (ycnts[i] + BETA * NUM_TOPICS)\n probs.append(x_prob * y_prob)\n new_y = sample_one(probs)\n ll += log(probs[new_y])\n add_counts(x, new_y, i, 1, xcnts, ycnts)\n ycorps[i][j] = new_y\n\n print(ll)\n\nif __name__ == \"__main__\":\n sampling()","sub_path":"takahashi/tutorial09/learn_lda.py","file_name":"learn_lda.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"584702788","text":"#running incremental ILP for incremental number of RRHs\nimport simpy\nimport functools\nimport random as np\nimport time\nfrom enum import Enum\nimport numpy\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nimport batch_teste as lp\nimport pureBatchILP as plp\nimport copy\nimport simDynamicTemporalRRH as sim\n\n#util class\nutil = sim.Util()\n#keep the power consumption\npower_consumption = []\ninc_power_consumption = []\n#to count the activated resources\nactivated_nodes, activated_lambdas, activated_dus, activated_switchs, redirected = ([] for i in range(5))\n#to count the activated resources\ninc_activated_nodes, inc_activated_lambdas, inc_activated_dus, inc_activated_switchs, inc_redirected = ([] for i in range(5))\n#to control the number of RRHs in each run\nr = range(1,50)\n\n#method of the batch sequential scheduling\ndef seqBatch():\n\tcount_nodes, count_lambdas, count_dus, count_switches = (0 for i in range(4))\n\t#list of RRHs to be scheduled\n\trrhs = []\n\t#create the RRHs\n\tfor i in r:\n\t\trrhs.append(util.createRRHs(i,[],[],[]))\n\t#calls the ILP for each set of RRHs\n\tfor i in rrhs:\n\t\tilp = plp.ILP(i, range(len(i)), plp.nodes, plp.lambdas)\n\t\ts = ilp.run()\n\t\t#print(lp.nodeState)\n\t\tif s != None:\n\t\t\t#print(\"Optimal solution is: {}\".format(s.objective_value))\n\t\t\tsol = ilp.return_solution_values()\n\t\t\tilp.updateValues(sol)\n\t\t\tif redirected:\n\t\t\t\tredirected.append(sum((redirected[-1], len(sol.var_k))))\n\t\t\telse:\n\t\t\t\tredirected.append(len(sol.var_k))\n\t\t\tpower_consumption.append(util.getPowerConsumption(plp))\n\t\t\t#counts the current activated nodes, lambdas, DUs and switches\n\t\t\tfor i in plp.nodeState:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_nodes += 1\n\t\t\tactivated_nodes.append(count_nodes)\n\t\t\tfor i in plp.lambda_state:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_lambdas += 1\n\t\t\tactivated_lambdas.append(count_lambdas)\n\t\t\tfor i in plp.du_state:\n\t\t\t\tfor j in i:\n\t\t\t\t\tif j == 1:\n\t\t\t\t\t\tcount_dus += 1\n\t\t\tactivated_dus.append(count_dus)\n\t\t\tfor i in plp.switch_state:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_switches += 1\n\t\t\tactivated_switchs.append(count_switches)\n\t\t\tilp.resetValues()\n\t\t\tcount_nodes = 0\n\t\t\tcount_lambdas = 0\n\t\t\tcount_dus = 0\n\t\t\tcount_switches = 0\n\tilp.resetValues()\n\n#method for the sequential incremental\ndef seqInc():\n\tcount_nodes, count_lambdas, count_dus, count_switches = (0 for i in range(4))\n\trrhs = util.createRRHs(max(r),[],[],[])\n\tnp.shuffle(rrhs)\n\t#calls the ilp for each rrh on rrhs\n\tfor i in rrhs:\n\t\trrh_list = []\n\t\trrh_list.append(i)\n\t\t#print(\"Matrix is {}\".format(i.rrhs_matrix))\n\t\tilp = plp.ILP(rrh_list, range(0,1), plp.nodes, plp.lambdas)\n\t\ts = ilp.run()\n\t\tif s != None:\n\t\t\t#print(\"Optimal solution is: {}\".format(s.objective_value))\n\t\t\tsol = ilp.return_solution_values()\n\t\t\tilp.updateValues(sol)\n\t\t\tif inc_redirected:\n\t\t\t\tinc_redirected.append(sum((inc_redirected[-1], len(sol.var_k))))\n\t\t\telse:\n\t\t\t\tinc_redirected.append(len(sol.var_k))\n\t\t\tinc_power_consumption.append(util.getPowerConsumption(plp))\n\t\t\t#counts the current activated nodes, lambdas, DUs and switches\n\t\t\tfor i in plp.nodeState:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_nodes += 1\n\t\t\tinc_activated_nodes.append(count_nodes)\n\t\t\tfor i in plp.lambda_state:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_lambdas += 1\n\t\t\tinc_activated_lambdas.append(count_lambdas)\n\t\t\tfor i in plp.du_state:\n\t\t\t\tfor j in i:\n\t\t\t\t\tif j == 1:\n\t\t\t\t\t\tcount_dus += 1\n\t\t\tinc_activated_dus.append(count_dus)\n\t\t\tfor i in plp.switch_state:\n\t\t\t\tif i == 1:\n\t\t\t\t\tcount_switches += 1\n\t\t\tinc_activated_switchs.append(count_switches)\n\t\t\tcount_nodes = 0\n\t\t\tcount_lambdas = 0\n\t\t\tcount_dus = 0\n\t\t\tcount_switches = 0\n\t\telse:\n\t\t\tprint(\"noooo\")\n\nseqBatch()\nseqInc()\nprint(redirected)\nprint(inc_redirected)\nmin_power = min(min(power_consumption), min(inc_power_consumption))\nmax_power = max(max(power_consumption), max(inc_power_consumption))\nmin_lambdas = min(min(activated_lambdas), min(inc_activated_lambdas))\nmax_lambdas = max(max(activated_lambdas), max(inc_activated_lambdas))\nmin_nodes = min(min(activated_nodes), min(inc_activated_nodes))\nmax_nodes = max(max(activated_nodes), max(inc_activated_nodes))\nmin_dus = min(min(activated_dus), min(inc_activated_dus))\nmax_dus = max(max(activated_dus), max(inc_activated_dus))\nmin_switch = min(min(activated_switchs), min(inc_activated_switchs))\nmax_switch = max(max(activated_switchs), max(inc_activated_switchs))\nmin_redirected = min(min(redirected), min(inc_redirected))\nmax_redirected = max(max(redirected), max(inc_redirected))\n\n#generate the plots for power consumption\nplt.plot(power_consumption, label = \"Batch ILP\")\nplt.plot(inc_power_consumption, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(range(len(power_consumption))), max(range(len(power_consumption))), 5))\nplt.yticks(numpy.arange(min_power, max_power, 500))\nplt.ylabel('Power Consumption')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/power_consumption.png', bbox_inches='tight')\nplt.clf()\n\n#generate the plots for activated lambdas\nplt.plot(activated_lambdas, label = \"Batch ILP\")\nplt.plot(inc_activated_lambdas, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(r), max(r), 5))\nplt.yticks(numpy.arange(min_lambdas, max_lambdas+1, 1))\nplt.ylabel('Activated Lambdas')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/activated_lambdas.png', bbox_inches='tight')\nplt.clf()\n\n#generate the plots for activated nodes\nplt.plot(activated_nodes, label = \"Batch ILP\")\nplt.plot(inc_activated_nodes, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(r), max(r), 5))\nplt.yticks(numpy.arange(min_nodes, max_nodes+1, 1))\nplt.ylabel('Activated Nodes')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/activated_nodes.png', bbox_inches='tight')\nplt.clf()\n\n#generate the plots for activated DUs\nplt.plot(activated_dus, label = \"Batch ILP\")\nplt.plot(inc_activated_dus, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(r), max(r), 5))\nplt.yticks(numpy.arange(min_dus, max_dus, 5))\nplt.ylabel('Activated DUs')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/activated_DUs.png', bbox_inches='tight')\nplt.clf()\n\n#generate the plots for activated Switches\nplt.plot(activated_switchs, label = \"Batch ILP\")\nplt.plot(inc_activated_switchs, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(r), max(r), 5))\nplt.yticks(numpy.arange(min_switch, max_switch+1, 1))\nplt.ylabel('Activated Switches')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/activated_switches.png', bbox_inches='tight')\nplt.clf()\n\n#generate the plots for redirected DUs\nplt.plot(redirected, label = \"Batch ILP\")\nplt.plot(inc_redirected, label = \"Inc ILP\")\nplt.xticks(numpy.arange(min(r), max(r), 5))\nplt.yticks(numpy.arange(min_redirected, max_redirected, 2))\nplt.ylabel('Redirected RRHs')\nplt.xlabel(\"Number of ONUs\")\nplt.legend()\nplt.grid()\nplt.savefig('/home/tinini/Área de Trabalho/simQuaseFinal/CFRAN-Simulator/experiments/redirected_rrhs.png', bbox_inches='tight')\nplt.clf()\n","sub_path":"inc_staticRRHs.py","file_name":"inc_staticRRHs.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"66504479","text":"from codewars.test import Test\n\ndef find_it(seq):\n num_count = {}\n for idx, num in enumerate(seq):\n if num in num_count:\n continue\n else:\n num_count[num] = seq.count(num)\n\n for key, val in num_count.items():\n if val % 2 != 0:\n return int(key)\n\ntest = Test()\n# test.describe(\"Example\")\ntest.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)\n","sub_path":"codewars/6kyu/findodd.py","file_name":"findodd.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"361328756","text":"#========================================================================\n# argv[1]: code\n# argv[2]: valid_path\n# argv[3]: rank\n# argv[4]: session / user\n#========================================================================\nimport sys\ntry:\n code = int(sys.argv[1])\nexcept IndexError:\n code=0\nexcept ValueError:\n pass\nwin_path = f'../features/4_winner/'\nsecond_path = '../features/2_second_valid/'\ngdrive_path = '../features/9_gdrive/'\nignore_list = []\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport shutil\nimport glob\nimport re\nHOME = os.path.expanduser('~')\nsys.path.append(f\"{HOME}/kaggle/data_analysis/library/\")\nimport utils\nfrom utils import logger_func\n\n# path rename\n# win_path = '../features/4_winner/*.gz'\n# path_list = glob.glob(win_path)\n# for path in path_list:\n# tmp = utils.read_pkl_gzip(path)\n# if path.count('107_his_train_'):\n# utils.to_pkl_gzip(path=path.replace(r'107_his_train_', '107_his_train_his_'), obj=tmp)\n# elif path.count('107_his_test_'):\n# utils.to_pkl_gzip(path=path.replace(r'107_his_test_', '107_his_test_his_'), obj=tmp)\n# sys.exit()\n\n\ndef to_win_dir_Nfeatures(path='../features/1_first_valid/*.gz', N=100):\n path_list = glob.glob(path)\n np.random.seed(1208)\n np.random.shuffle(path_list)\n path_list = path_list[:N]\n for path in path_list:\n try:\n shutil.move('train_'+path, win_path)\n shutil.move('test_'+path, win_path)\n except shutil.Error:\n shutil.move('train_'+path, '../features/9_delete')\n shutil.move('test_'+path, '../features/9_delete')\n\n\ndef move_to_second_valid(best_select=[], path='', rank=0, key_list=[]):\n logger = logger_func()\n if len(best_select)==0:\n try:\n if path=='':\n path = sys.argv[2]\n except IndexError:\n pass\n best_select = pd.read_csv(path)\n try:\n if rank==0:\n rank = int(sys.argv[3])\n except IndexError:\n pass\n best_feature = best_select.query(f\"rank>={rank}\")['feature'].values\n try:\n best_feature = [col for col in best_feature if col.count(sys.argv[4])]\n except IndexError:\n best_feature = [col for col in best_feature if col.count('')]\n\n if len(best_feature)==0:\n sys.exit()\n\n path_list = glob.glob('../features/4_winner/*')\n\n for feature in best_feature:\n move_path = []\n for path in path_list:\n filename = re.search(r'/([^/.]*).gz', path).group(1)\n # if path.count(feature) and feature not in ignore_list:\n # if feature==filename:\n if feature==filename.replace('stan_', ''):\n # print(f\"{filename} | {feature}\")\n move_path.append(path)\n\n for move in move_path:\n try:\n shutil.move(move, second_path)\n except FileNotFoundError:\n logger.info(f'FileNotFoundError: {feature}')\n except shutil.Error:\n logger.info(f'Shutil Error: {feature}')\n print(f'move to third_valid:{len(best_feature)}')\n\n\ndef move_to_use():\n\n try:\n path = sys.argv[2]\n except IndexError:\n path = ''\n best_select = pd.read_csv(path)\n best_feature = best_select['feature'].values\n\n win_list = glob.glob(win_path + '*')\n first_list = glob.glob('../features/1_first_valid/*')\n second_list = glob.glob('../features/2_second_valid/*')\n third_list = glob.glob('../features/3_third_valid/*')\n tmp_list = glob.glob('../features/5_tmp/*')\n path_list = third_list\n # path_list = third_list + tmp_list + win_list\n # path_list = first_list + second_list + third_list + tmp_list + win_list\n\n done_list = []\n for feature in best_feature:\n for path in path_list:\n try:\n filename = re.search(r'/([^/.]*).gz', path).group(1)\n except AttributeError:\n continue\n # if path.count(feature):\n # if filename==feature:\n if filename.replace('stan_', '')==feature:\n try:\n shutil.move(path, win_path)\n # filename = re.search(r'/([^/.]*).gz', path).group(1)\n done_list.append(filename)\n except shutil.Error:\n pass\n # shutil.move(path, gdrive_path)\n except FileNotFoundError:\n pass\n # shutil.move(path, gdrive_path)\n\n logger = logger_func()\n best_feature = [f for f in best_feature]\n\n loss_list = set(list(best_feature)) - set(done_list)\n logger.info(f\"Loss List:\")\n for loss in loss_list:\n logger.info(f\"{loss}\")\n\n\ndef move_feature(feature_name, move_path='../features/9_delete'):\n\n try:\n shutil.move(f'../features/4_winner/{feature_name}.gz', move_path)\n except FileNotFoundError:\n print(f'FileNotFound. : {feature_name}.gz')\n pass\n\n\ndef main():\n if code==0:\n move_to_second_valid()\n elif code==1:\n move_to_use()\n elif code==2:\n move_file()\n elif code==4:\n to_win_dir_Nfeatures(N=int(sys.argv[2]))\n\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"py/select_feature.py","file_name":"select_feature.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"80437305","text":"# *****************************************************************************\n# Copyright (c) 2019, Intel Corporation All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# *****************************************************************************\n\n\"\"\"\n\n| :class:`pandas.SeriesGroupBy` functions and operators implementations in SDC\n| Also, it contains Numba internal operators which are required for :class:`pandas.SeriesGroupBy` type handling\n\n\"\"\"\n\n\nimport numpy\nimport pandas\n\nfrom numba import types\nfrom numba.extending import overload_method\nfrom numba.errors import TypingError\n\nfrom sdc.datatypes.hpat_pandas_seriesgroupby_types import SeriesGroupByType\n\n\n@overload_method(SeriesGroupByType, 'count')\ndef hpat_pandas_seriesgroupby_count(self):\n \"\"\"\n Pandas Series method :meth:`pandas.core.groupby.GroupBy.count` implementation.\n\n .. only:: developer\n\n Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_groupby_count\n\n Parameters\n -----------\n self: :obj:`pandas.core.groupby.SeriesGroupBy`\n The object this method is working on\n\n Returns\n -------\n :obj:`pandas.Series`\n returns :obj:`pandas.Series` object with count of values within each group\n \"\"\"\n\n _func_name = 'Method seriesgroupby.count().'\n\n if not isinstance(self, SeriesGroupByType):\n raise TypingError('{} The object must be a pandas.seriesgroupby. Given: {}'.format(_func_name, self))\n\n def hpat_pandas_seriesgroupby_count_impl(self):\n \"\"\"\n Pandas algorithm:\n https://github.com/pandas-dev/pandas/blob/b1049540fe207f8d8071ebfbd44e8f5224c98bad/pandas/core/groupby/generic.py#L1339\n \"\"\"\n\n # is not implemented yet.\n # return self._data.value_counts()\n #\n # workaround\n freq = {}\n for x in self._data:\n if x not in freq:\n freq[x] = 1\n else:\n freq[x] += 1\n\n # Numba requires to translate dict() into list()\n keys = []\n values = []\n for key, value in freq.items():\n keys.append(key)\n values.append(value)\n\n return pandas.Series(values, keys)\n\n return hpat_pandas_seriesgroupby_count_impl\n","sub_path":"sdc/datatypes/hpat_pandas_seriesgroupby_functions.py","file_name":"hpat_pandas_seriesgroupby_functions.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"99055669","text":"import ROOT\n\n\ndef prtStable(pid):\n return abs(pid) in (211, 321, 11, 13, 2212)\n\n\ndef heavyFlavor(pid):\n return abs(pid) in (411, 421, 431, 4122, 511, 521, 531, 5122)\n\n\n# Writer class.\nclass Writer:\n def __init__(self):\n from collections import OrderedDict\n\n self.vars = OrderedDict()\n self.null = ROOT.vector(\"double\")(1, 0)\n\n def init(self, tree):\n for key, val in self.vars.iteritems():\n tree.Branch(key, val)\n\n def add(self, var):\n self.vars[var] = ROOT.vector(\"double\")()\n\n def var(self, var, val=None, idx=-2):\n if not var in self.vars:\n return self.null.back()\n var = self.vars[var]\n if idx < -1:\n var.push_back(0 if val == None else val)\n if idx < 0:\n idx = var.size() - 1\n elif idx >= var.size():\n idx = -1\n if idx < 0:\n return self.null[0]\n if val != None:\n var[idx] = val\n return var[idx]\n\n def size(self, var):\n return self.vars[var].size()\n\n def clear(self):\n for key, val in self.vars.iteritems():\n val.clear()\n\n\ndef hitSel(mhit, fhit, pz):\n hit = mhit\n hit_type = -1\n if mhit.T() != 0:\n hit_type = 0\n if mhit.T() == 0 and fhit.T() != 0:\n hit = fhit\n hit_type = 1\n elif fhit.T() != 0 and (pz / abs(pz)) * fhit.Z() < (pz / abs(pz)) * mhit.Z():\n hit = fhit\n hit_type = 1\n return [hit.X(), hit.Y(), hit.Z(), hit_type]\n\n\ndef Hits(module, rffoil, scatter, prt):\n hits = []\n p = prt.pAbs()\n if p == 0:\n return hits\n vx, vy, vz = prt.xProd(), prt.yProd(), prt.zProd()\n px, py, pz = prt.px() / p, prt.py() / p, prt.pz() / p\n p3 = ROOT.TVector3(prt.px(), prt.py(), prt.pz())\n nrf = 0\n mhit = module.intersect(vx, vy, vz, px, py, pz)\n fhit = rffoil.intersect(vx, vy, vz, px, py, pz)\n hit = hitSel(mhit, fhit, pz)\n while hit[3] >= 0:\n vx, vy, vz = [hit[0], hit[1], hit[2]]\n if hit[3] == 0:\n hits += [[vx, vy, vz]]\n fx0 = 0.01\n if hit[3] > 0:\n nrf += 1\n fx0 = 0.005\n p3 = scatter.smear(p3, fx0)\n px, py, pz = p3.X() / p3.Mag(), p3.Y() / p3.Mag(), p3.Z() / p3.Mag()\n vx, vy, vz = vx + px * 0.1, vy + py * 0.1, vz + pz * 0.1\n mhit = module.intersect(vx, vy, vz, px, py, pz)\n fhit = rffoil.intersect(vx, vy, vz, px, py, pz)\n hit = hitSel(mhit, fhit, pz)\n return hits\n","sub_path":"gen/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307937575","text":"#!/apollo/sbin/envroot \"$ENVROOT/python3.6/bin/python3.6\"\n\nimport re\nimport sys\nimport os\nimport argparse\nimport git\nimport logging\nfrom dxd_tools_dev.modules import mcm\nfrom dxd_tools_dev.modules import mcm_variables\n\nlogging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)\n\ndef parse_args(fake_args=None):\n main_parser = argparse.ArgumentParser(prog='acl_manage_mcm.py')\n main_parser.add_argument(\"-pl\", \"--prefix_list_devices\", type=str, dest=\"prefix_list_devices\", required=True, help=\"Comma separated vc-car/vc-dar device names\")\n main_parser.add_argument(\"-no_plu\", \"--no_prefix_list_update\", default=True, action='store_false', dest=\"no_prefix_list_update\", help=\"Specify -no_plu flag to not update prefix lists. Prefix list will be updated by default (if -no_plu is not specified)\")\n main_parser.add_argument(\"-vccor\", \"--vc_cor_brick\", type=str, dest=\"vc_cor_brick\", help=\"VC_COR brick on which ACLs need to be deployed\")\n main_parser.add_argument(\"-brtra\", \"--br_tra_devices\", type=str, dest=\"br_tra_devices\", help=\"Comma separated br-tra devices on which ACLs need to be deployed\")\n main_parser.add_argument(\"-ae\", \"--ae_interfaces\", type=str, dest=\"ae_interfaces\", help=\"Comma separated ae interfaces - e.g ae30,ae31\")\n main_parser.add_argument(\"-dae\", \"--dx2_ae_interfaces\", type=str, dest=\"dx2_ae_interfaces\", help=\"Comma separated ae interfaces toward vc-bdr - e.g ae30,ae31\")\n main_parser.add_argument(\"-bp\", \"--bgp_prestaged\", type=str, default=\"True\", help=\"set to True if BGP is prestaged, else False. Default is True\")\n main_parser.add_argument(\"-sb\", \"--ssh_bastion\", type=str, dest=\"ssh_bastion\", required=True, help=\"SSH BASTION e.g neteng-bastion-iad-6004.iad6.amazon.com\")\n main_parser.add_argument(\"-adv\", \"--add_devices\", default=False, action='store_true', dest=\"add_devices\", help=\"Optional - use this flag for adding devices to ACL Manage\")\n return main_parser.parse_args()\n\ndef git_clone(package, path= \"/home/\" + os.getlogin() + \"/\"):\n full_path = path + package\n full_url = 'ssh://git.amazon.com/pkg/' + package\n try:\n repo = git.Repo.clone_from(full_url ,to_path = f'{full_path}')\n return repo\n except:\n logging.error('Could not clone {}. Exception {}'.format(package, sys.exc_info()))\n return None\n\ndef main():\n cli_arguments = parse_args()\n\n logging.info('Checking User provided input devices')\n\n if not cli_arguments.ae_interfaces and not cli_arguments.dx2_ae_interfaces:\n print( '-ae/--ae_interfaces and -dae/--dx2_ae_interfaces are missing. you need to specify atleast one')\n raise\n\n if cli_arguments.vc_cor_brick and cli_arguments.br_tra_devices:\n logging.error('vc-cor and br-tra both passed as arguments. Please specify either vc-cor or br-tra and re-run the script. Existing')\n sys.exit()\n\n for device in cli_arguments.prefix_list_devices.split(','):\n if not re.match('.*-vc-(car|dar|bdr)-.*', device):\n raise ValueError('Device not supported. {} must be VC-CAR or VC-DAR or VC-BDR'.format(cli_arguments.vc_car_dar_devices))\n\n if cli_arguments.vc_cor_brick:\n if not re.search('^[a-z][a-z][a-z][0-9][0-9]?-vc-cor-b[0-9]$',cli_arguments.vc_cor_brick):\n raise ValueError('Specify vc-cor brick. It should follow {site}-vc-cor-b{brick_number} standard')\n deploy_acl_devices = cli_arguments.vc_cor_brick + '-r1,' + cli_arguments.vc_cor_brick + '-r2,' + cli_arguments.vc_cor_brick + '-r3,' + cli_arguments.vc_cor_brick + '-r4'\n\n if cli_arguments.br_tra_devices:\n for device in cli_arguments.br_tra_devices.split(','):\n if not re.match('.*-br-tra-.*', device):\n raise ValueError('Device not supported. {} must be comma separated br-tra'.format(cli_arguments.br_tra_devices))\n deploy_acl_devices = cli_arguments.br_tra_devices\n\n\n\n\n logging.info('Creating variable file')\n ae_interfaces = ''\n dx2_ae_interfaces = ''\n \n devices_vc_car_dar_bdr = cli_arguments.prefix_list_devices\n ssh_bastion = cli_arguments.ssh_bastion\n add_devices = cli_arguments.add_devices\n if cli_arguments.ae_interfaces:\n ae_interfaces = cli_arguments.ae_interfaces\n if cli_arguments.dx2_ae_interfaces:\n dx2_ae_interfaces = cli_arguments.dx2_ae_interfaces\n bgp_prestaged = cli_arguments.bgp_prestaged\n\n car_dar_counter = 0\n bdr_counter = 0\n\n for device in devices_vc_car_dar_bdr.split(','):\n if 'car' in device or 'dar' in device:\n car_dar_counter += 1\n elif 'bdr' in device:\n bdr_counter += 1\n\n if car_dar_counter != 0:\n no_prefix_list_update = cli_arguments.no_prefix_list_update\n else:\n no_prefix_list_update = False\n\n variable_file = mcm_variables.create_variables_vc_cor_acl_manage(no_prefix_list_update,devices_vc_car_dar_bdr,deploy_acl_devices,ae_interfaces,dx2_ae_interfaces,ssh_bastion,add_devices,bgp_prestaged)\n logging.info('variable file created')\n\n logging.info('Creating MCM')\n\n if bdr_counter == 0:\n mcm_info = mcm.mcm_creation(\"acl_manage\",no_prefix_list_update,devices_vc_car_dar_bdr,deploy_acl_devices)\n else: \n mcm_info = mcm.mcm_creation(\"dx2_acl_manage\",no_prefix_list_update,devices_vc_car_dar_bdr,deploy_acl_devices)\n mcm_id = mcm_info[0]\n mcm_uid = mcm_info[1]\n mcm_overview = mcm_info[2]\n logging.info('https://mcm.amazon.com/cms/{} created'.format(mcm_id))\n\n logging.info('Updating variable file with MCM number')\n variable_file_updated = variable_file.replace('MCM_NUMBER',mcm_id)\n logging.info('variable file updated')\n\n # git operations\n logging.info('Performing git operations')\n username = os.getlogin()\n if os.path.exists(f'/home/{username}/DxVpnCM2014/') == True:\n repo = git.Repo(f'/home/{username}/DxVpnCM2014')\n origin = repo.remote('origin')\n logging.info('DxVpnCM2014 repo exists')\n if os.path.exists(f'/home/{username}/DxVpnCM2014/cm/{username}') == True:\n logging.info('{} exists under DxVpnCM2014/cm directory'.format(username))\n logging.info('Performing git pull')\n origin.pull()\n else:\n logging.info('{} does not exists under DxVpnCM2014/cm directory'.format(username))\n os.mkdir(f'/home/{username}/DxVpnCM2014/cm/{username}')\n logging.info('User {} successfully created user directory under DxVpnCM2014/cm'.format(username))\n logging.info('Performing git pull')\n origin.pull()\n else:\n logging.info('DxVpnCM2014 repo does not exist')\n logging.info('Performing git clone on DxVpnCM2014')\n cloned = git_clone('DxVpnCM2014')\n\n if cloned:\n logging.info('git clone successful for DxVpnCM2014')\n repo = git.Repo(f'/home/{username}/DxVpnCM2014')\n origin = repo.remote('origin')\n if os.path.exists(f'/home/{username}/DxVpnCM2014/cm/{username}') == True:\n logging.info('{} exists under DxVpnCM2014/cm directory'.format(username))\n logging.info('Performing git pull')\n origin.pull()\n else:\n logging.info('{} does not exists under DxVpnCM2014/cm directory'.format(username))\n os.mkdir(f'/home/{username}/DxVpnCM2014/cm/{username}')\n logging.info('User {} successfully created user directory under DxVpnCM2014/cm'.format(username))\n logging.info('Performing git pull')\n origin.pull()\n else:\n logging.error('git clone failed for DxVpnCM2014. Clone DxVpnCM2014 manually and re-run the script')\n sys.exit()\n\n os.mkdir(f'/home/{username}/DxVpnCM2014/cm/{username}/{mcm_id}')\n with open(f'/home/{username}/DxVpnCM2014/cm/{username}/{mcm_id}/{mcm_id}.var','w') as var_file:\n var_file.write(variable_file_updated)\n var_file.close()\n\n logging.info(f'Created variable file for Daryl /home/{username}/DxVpnCM2014/cm/{username}/{mcm_id}/{mcm_id}.var')\n logging.info('Prepping for variable file to be pushed to DxVpnCM2014 repo')\n repo = git.Repo(f'/home/{username}/DxVpnCM2014')\n logging.info('git add')\n repo.index.add([f'/home/{username}/DxVpnCM2014/cm/{username}/{mcm_id}/{mcm_id}.var'])\n logging.info('git status\\n{}\\n'.format(repo.git.status()))\n logging.info('git commit')\n repo.index.commit(f'variable file for {mcm_id}')\n origin = repo.remote('origin')\n logging.info('git push')\n origin.push()\n logging.info('variable file /home/{}/DxVpnCM2014/cm/{}/{}/{}.var successfully pushed to DxVpnCM2014 repo'.format(username,username,mcm_id,mcm_id))\n\n mcm_overview_append = f\"\"\"\n###Lock MCM\n```\n/apollo/env/Daryl/bin/darylscriptc --lock --cm {mcm_id}\n ```\n\n###Dry-run\n```\n/apollo/env/Daryl/bin/daryl.pl --cm {mcm_id} --mode dryrun --no-auto-dashboard --no-hds\n ```\n\n###Execute MCM\n```\n/apollo/env/Daryl/bin/daryl.pl --cm {mcm_id} --mode execute\n```\n\n###Variable File\n\nhttps://code.amazon.com/packages/DxVpnCM2014/blobs/mainline/--/cm/{username}/{mcm_id}/{mcm_id}.var\n\n \"\"\"\n # update MCM overview and steps\n mcm_overview_final = mcm_overview + mcm_overview_append\n mcm_steps = [{'title':'Daryl Info','time':300,'description':f'Daryl URL: brazil://DxVpnCM2014/cm/{username}/{mcm_id}/{mcm_id}.var'}]\n mcm.mcm_update(mcm_id,mcm_uid,mcm_overview_final,mcm_steps)\n logging.info('{} successfully updated, please lock the MCM through Daryl and submit for approvals\\n'.format(mcm_id))\n\nif __name__ == '__main__':\n main()\n","sub_path":"aws/acl_manage_mcm.py","file_name":"acl_manage_mcm.py","file_ext":"py","file_size_in_byte":9606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"573185452","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ja', '0003_auto_20160125_1353'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='articles',\n options={'verbose_name': 'Artykuł', 'verbose_name_plural': 'Artykuły', 'ordering': ['date']},\n ),\n ]\n","sub_path":"ja/migrations/0004_auto_20160125_1354.py","file_name":"0004_auto_20160125_1354.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"319029473","text":"#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), 'code'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n\n#%%\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport pytesseract\nimport cv2\nimport os\nimport glob\nimport matplotlib.pyplot as plt\n\nos.chdir('..')\nos.chdir('Images')\nf = open('./list.txt', 'r')\ncategories = f.read().split('\\n')[:-1]\ncategories.sort()\n\n\n#%%\nfor i, category in enumerate(categories):\n print(category)\n for name in glob.glob('./' + category + '/*'):\n img = cv2.imread(name)\n \n b, g, r = cv2.split(img)\n img = cv2.merge([r, g, b]) \n \n plt.imshow(img)\n plt.show()\n print(pytesseract.image_to_string(img, lang='Hangul'))\n\n\n#%%\n\n\n\n\n","sub_path":"code/.ipynb_checkpoints/ocr_notebook-checkpoint.py","file_name":"ocr_notebook-checkpoint.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"168800597","text":"import hashlib\nimport os\n\ndef md5(fname):\n \"\"\"\n Creates a md5sum hash from filepath to be used for checksum\n \"\"\"\n hashmd5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hashmd5.update(chunk)\n return hashmd5.hexdigest()\n\ndef compareMD5(file1, file2):\n \"\"\"\n Compares between 2 MD5SUM hash to compare between file\n \"\"\"\n if file1 == file2:\n return True\n else:\n return False\n\ndef grab_files(directory):\n \"\"\"\n Traverses from the top directory and returns a list containing the file\n name and file path\n \"\"\"\n arrPath = []\n for root, dirs, files in os.walk(directory):\n for name in files:\n filedir = os.path.join(root,name) \n arrPath.append((filedir))\n return arrPath\n\ndef createFile(arrPath,name='MD5SUM.txt'):\n \"\"\"\n Create file containing name and md5sum value\n \"\"\"\n filetext = open(name, mode='w+')\n for name, filedir in arrPath:\n print(name, filedir, file=filetext)\n\ndef compareLocalMD5(path = None, checksum1 = 'MD5SUM.txt'):\n \"\"\"\n Compares local file with latest MD5SUM. Input must be in the form of string\n ex: .\\thisFolder\n \"\"\"\n # Creates the md5 of local content\n files_in_dir = grab_files(path)\n local_list = [] # List of filenames and its md5 value\n for i in files_in_dir:\n y = md5(i)\n local_list.append((i,y))\n local_dict = dict(local_list) # Change it to a dictionary\n\n # Open the previously created MD5SUM\n fileMD = open(checksum1, \"r\").read()\n listMD = fileMD.split(\"\\n\")\n temp =[]\n for i in listMD:\n temp.append(i[:-33])\n temp.append(i[-32:])\n listMD = temp\n dictMD = dict(zip(*[iter(listMD)]*2))\n try:\n dictMD.pop(\"\",None)\n except:\n pass\n \n \n # Determine which files are missing/created anew\n result = []\n for key in dictMD:\n if key in local_dict:\n if dictMD[key] == local_dict[key]: \n result.append((key, \"MATCH\"))\n elif dictMD[key] != local_dict[key]:\n result.append((key, \"UPDATE\"))\n if key not in local_dict:\n result.append((key, \"DELETE\"))\n for key in local_dict:\n if key not in dictMD:\n result.append((key, \"UPLOAD\"))\n return result\n \n \ndef compareFileDifference(checksum1 = None, checksum2 = None):\n \"\"\"\n Compare actual file difference and\n return a list with status of file\n \"\"\"\n # Open Files\n fileMD = open(checksum1, \"r\").read()\n fileMDOutput = open(checksum2, \"r\").read()\n # Split 'em and put 'em as dicks\n listMD = fileMD.split(\"\\n\")\n listMDOutput = fileMDOutput.split(\"\\n\")\n\n temp =[]\n for i in listMD:\n temp.append(i[:-33])\n temp.append(i[-32:])\n listMD = temp\n temp =[]\n for i in listMDOutput:\n temp.append(i[:-33])\n temp.append(i[-32:])\n listMDOutput = temp\n\n dictMD = dict(zip(*[iter(listMD)]*2))\n dictMDOutput = dict(zip(*[iter(listMDOutput)]*2))\n \n \n # Determine which have the same key and same md5 value\n result = []\n for key in dictMD:\n if key in dictMDOutput:\n if dictMD[key] == dictMDOutput[key]: \n result.append((key, \"MATCH\"))\n elif dictMD[key] != dictMDOutput[key]:\n result.append((key, \"MISMATCH\"))\n if key not in dictMDOutput:\n result.append((key, \"MISSINGCLIENT\"))\n for key in dictMDOutput:\n if key not in dictMD:\n result.append((key, \"MISSINGSERVER\"))\n return result\n\n\n\n## x = md5sum.grab_files(FILE_PATH)\n## lista = []\n## for i in x:\n## y = md5sum.md5(i)\n## lista.append((i,y))\n## md5sum.createFile(lista)\n\n\n\n \n","sub_path":"Desktop/Server/md5sum.py","file_name":"md5sum.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"576291581","text":"def main():\r\n fruits = ['banana','apple','pear','waxberry']\r\n fruits += ['pineapple','greap','mango']\r\n\r\n for fruit in fruits:\r\n print(fruit.title(), end = ' ')\r\n print()\r\n\r\n #sort函数不会修改传入列表\r\n fruits_sort1 = sorted(fruits)\r\n fruits_sort2 = sorted(fruits, reverse = True)\r\n fruits_sort3 = sorted(fruits, key = len)\r\n\r\n print(fruits_sort1)\r\n print(fruits_sort2)\r\n print(fruits_sort3)\r\n\r\n #在原列表上进行排序\r\n fruits.sort(reverse = True)\r\n print(fruits)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"python_study/基础结构与模块/列表排序.py","file_name":"列表排序.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"605565135","text":"from django.shortcuts import render, get_object_or_404,redirect\nfrom orders.models import OrderItem\nfrom orders.forms import OrderCreateForm\nfrom cart.cart import Cart\n\nfrom pages.models import Products,Sku\n\nfrom django.http import HttpResponse\nfrom django.core.mail import EmailMessage\nfrom django.core.mail import send_mail\n\n\n\n\nimport stripe # new\n\nfrom django.conf import settings\nfrom django.views.generic.base import TemplateView\nfrom django.shortcuts import render # new\n\nstripe.api_key = settings.STRIPE_SECRET_KEY # new\n\n\n\nclass HomePageView(TemplateView):\n template_name = 'homep.html'\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['key'] = settings.STRIPE_PUBLISHABLE_KEY\n return context\n\n\ndef charge(request): # new\n cart = Cart(request)\n amt=cart.get_total_price2()\n print(amt)\n if request.method == 'POST':\n\n charge = stripe.Charge.create(\n amount=int(amt),\n currency='usd',\n description='A Django charge',\n source=request.POST['stripeToken']\n \n )\n\n\n\n \n\n\n\n\n\n\n status='success'\n context={'status':status,}\n \n #return render(request, 'charge.html',context)\n return redirect('payments:order_create')\n\ndef callback(request):\n \n #profile = UserProfile.objects.get(user=request.user)\n\n r = request.POST('https://connect.stripe.com/oauth/token', params={\n 'client_secret': settings.STRIPE_SECRET_KEY\n \n }).json()\n\n try:\n access_token = r['access_token']\n refresh_token = r['refresh_token']\n publishable_key = r['stripe_publishable_key']\n #profile.save()\n\n messages.success(request, \"Your account was successfully connected to Stripe.\")\n except KeyError:\n messages.error(request, \"Unable to connect your account to Stripe.\")\n\n return redirect('homep')\n\ndef order_create(request):\n #cart=scart\n \n cart = Cart(request)\n\n \n print(cart.cart)\n #request.session['cart']=cart\n if request.method == 'POST':\n print('start to work on db')\n form = OrderCreateForm(request.POST)\n if form.is_valid():\n order = form.save(False)\n for item in cart:\n print(item)\n product_id=item['product_id']\n quantity=item['quantity'] \n product = get_object_or_404(Products, id=product_id)\n sproduct = Sku.objects.filter(product= product,colour=item['color'],size=item['size'])\n if sproduct.count() == 0:\n stock=0\n \n else:\n \n order = form.save()\n stock=sproduct[0].stock\n OrderItem.objects.create(\n order=order,\n product=product,\n price=item['price'],\n size=item['size'],\n colour=item['color'],\n quantity=item['quantity'],\n )\n print(sproduct[0].stock)\n id=sproduct[0].id\n print(id)\n newq=Sku.objects.get(id=id)\n newstock=int(sproduct[0].stock)-quantity\n newq.stock=newstock\n newq.save()\n print('after:'+str(newstock))\n \n \n \n cart.clear()\n #return redirect('payments:homep')\n return render(request, 'orders/order/created.html', {'order': order, 'cart':cart})\n else:\n form = OrderCreateForm()\n print('blank')\n return render(request, 'homep.html', {'form': form, 'cart':cart,})","sub_path":"payments/viewsb4updatetran.py","file_name":"viewsb4updatetran.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"464128851","text":"import time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nimport utils\n\n# logging setup\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(levelname)s - %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\nclass Trainer(object):\n\n def __init__(self, model, eta, mom, no_loss_reg, vec_dim, cuda=False):\n # set the random seeds for every instance of trainer.\n # needed to ensure reproduction of random word vectors for out of vocab terms\n torch.manual_seed(1234)\n np.random.seed(1234)\n self.cuda = cuda\n self.unk_term = np.random.uniform(-0.25, 0.25, vec_dim)\n\n self.reg = 1e-5\n self.no_loss_reg = no_loss_reg\n self.model = model\n self.criterion = nn.CrossEntropyLoss()\n #self.criterion = nn.NLLLoss()\n self.optimizer = optim.SGD(self.model.parameters(), lr=eta, momentum=mom, \\\n weight_decay=(0 if no_loss_reg else self.reg))\n\n self.data_splits = {}\n self.embeddings = {}\n self.vec_dim = vec_dim\n\n\n def load_input_data(self, dataset_root_folder, word_vectors_cache_file, \\\n train_set_folder, dev_set_folder, test_set_folder, load_ext_feats=True):\n for set_folder in [test_set_folder, dev_set_folder, train_set_folder]:\n if set_folder:\n questions, sentences, labels, maxlen_q, maxlen_s, vocab = \\\n utils.read_in_dataset(dataset_root_folder, set_folder)\n\n self.data_splits[set_folder] = [questions, sentences, labels, maxlen_q, maxlen_s]\n\n default_ext_feats = [np.zeros(4)] * len(self.data_splits[set_folder][0])\n self.data_splits[set_folder].append(default_ext_feats)\n\n utils.load_cached_embeddings(word_vectors_cache_file, vocab, self.embeddings,\n [] if \"train\" in set_folder else self.unk_term)\n\n\n def regularize_loss(self, loss):\n\n flattened_params = []\n\n for p in self.model.parameters():\n f = p.data.clone()\n flattened_params.append(f.view(-1))\n\n fp = torch.cat(flattened_params)\n\n loss = loss + 0.5 * self.reg * fp.norm() * fp.norm()\n\n # for p in self.model.parameters():\n # loss = loss + 0.5 * self.reg * p.norm() * p.norm()\n\n return loss\n\n\n def _train(self, xq, xa, ext_feats, ys):\n\n self.optimizer.zero_grad()\n output = self.model(xq, xa, ext_feats)\n loss = self.criterion(output, ys)\n # logger.debug('loss after criterion {}'.format(loss))\n\n # NOTE: regularizing location 1\n if not self.no_loss_reg:\n loss = self.regularize_loss(loss)\n # logger.debug('loss after regularizing {}'.format(loss))\n\n loss.backward()\n\n # logger.debug('AFTER backward')\n #logger.debug('params {}'.format([p for p in self.model.parameters()]))\n # logger.debug('params grads {}'.format([p.grad for p in self.model.parameters()]))\n\n # NOTE: regularizing location 2. It would seem that location 1 is correct?\n #if not self.no_loss_reg:\n # loss = self.regularize_loss(loss)\n # logger.debug('loss after regularizing {}'.format(loss))\n\n self.optimizer.step()\n\n # logger.debug('AFTER step')\n #logger.debug('params {}'.format([p for p in self.model.parameters()]))\n # logger.debug('params grads {}'.format([p.grad for p in self.model.parameters()]))\n\n return loss.data[0], self.pred_equals_y(output, ys)\n\n\n def pred_equals_y(self, pred, y):\n _, best = pred.max(1)\n best = best.data.long().squeeze()\n return torch.sum(y.data.long() == best)\n\n\n def test(self, set_folder, batch_size):\n logger.info('----- Predictions on {} '.format(set_folder))\n\n questions, sentences, labels, maxlen_q, maxlen_s, ext_feats = \\\n self.data_splits[set_folder]\n word_vectors, vec_dim = self.embeddings, self.vec_dim\n\n self.model.eval()\n\n batch_size = 1\n\n total_loss = 0.0\n total_correct = 0.0\n num_batches = np.ceil(len(questions)/batch_size)\n y_pred = np.zeros(len(questions))\n ypc = 0\n\n for k in range(int(num_batches)):\n batch_start = k * batch_size\n batch_end = (k+1) * batch_size\n # convert raw questions and sentences to tensors\n batch_inputs, batch_labels = self.get_tensorized_inputs(\n questions[batch_start:batch_end],\n sentences[batch_start:batch_end],\n labels[batch_start:batch_end],\n ext_feats[batch_start:batch_end],\n word_vectors, vec_dim\n )\n\n xq, xa, x_ext_feats = batch_inputs[0]\n y = batch_labels[0]\n\n pred = self.model(xq, xa, x_ext_feats)\n loss = self.criterion(pred, y)\n pred = torch.exp(pred)\n total_loss += loss\n # total_correct += self.pred_equals_y(pred, y)\n\n y_pred[ypc] = pred.data.squeeze()[1]\n # ^ we want to score for relevance, NOT the predicted class\n ypc += 1\n\n # logger.info('{}_correct {}'.format(set_folder, total_correct))\n # logger.info('{}_loss {}'.format(set_folder, total_loss.data[0]))\n logger.info('{} total {}'.format(set_folder, len(labels)))\n # logger.info('{}_loss = {:.4f}, acc = {:.4f}'.format(set_folder, total_loss.data[0]/len(labels), float(total_correct)/len(labels))\n #logger.info('{}_loss = {:.4f}'.format(set_folder, total_loss.data[0]/len(labels)))\n\n return y_pred\n\n\n def train(self, set_folder, batch_size, debug_single_batch):\n train_start_time = time.time()\n\n questions, sentences, labels, maxlen_q, maxlen_s, ext_feats = \\\n self.data_splits[set_folder]\n word_vectors, vec_dim = self.embeddings, self.vec_dim\n\n # set model for training modep\n self.model.train()\n\n train_loss, train_correct = 0., 0.\n num_batches = np.ceil(len(questions)/float(batch_size))\n\n for k in range(int(num_batches)):\n batch_start = k * batch_size\n batch_end = (k+1) * batch_size\n\n # convert raw questions and sentences to tensors\n batch_inputs, batch_labels = self.get_tensorized_inputs(\n questions[batch_start:batch_end],\n sentences[batch_start:batch_end],\n labels[batch_start:batch_end],\n ext_feats[batch_start:batch_end],\n word_vectors, vec_dim\n )\n\n xq, xa, x_ext_feats = batch_inputs[0]\n\n ys = batch_labels[0]\n\n batch_loss, batch_correct = self._train(xq, xa, x_ext_feats, ys)\n\n # logger.debug('batch_loss {}, batch_correct {}'.format(batch_loss, batch_correct))\n train_loss += batch_loss\n # train_correct += batch_correct\n if debug_single_batch:\n break\n\n # logger.info('train_correct {}'.format(train_correct))\n logger.info('train_loss {}'.format(train_loss))\n logger.info('total training batches = {}'.format(num_batches))\n logger.info('train_loss = {:.4f}'.format(\n train_loss/num_batches\n ))\n logger.info('training time = {:.3f} seconds'.format(time.time() - train_start_time))\n return train_correct/num_batches\n\n\n def make_input_matrix(self, sentence, word_vectors, vec_dim):\n terms = sentence.strip().split()[:60]\n # NOTE: we are truncating the inputs to 60 words.\n\n word_embeddings = torch.zeros(len(terms), vec_dim).type(torch.DoubleTensor)\n for i in range(len(terms)):\n word = terms[i]\n emb = torch.from_numpy(word_vectors[word])\n word_embeddings[i] = emb\n\n input_tensor = torch.zeros(1, vec_dim, len(terms))\n input_tensor[0] = torch.transpose(word_embeddings, 0, 1)\n if self.cuda and torch.cuda.is_available():\n input_tensor = input_tensor.cuda()\n return input_tensor\n\n\n def get_tensorized_inputs(self, batch_ques, batch_sents, batch_labels, batch_ext_feats, \\\n word_vectors, vec_dim):\n batch_size = len(batch_ques)\n # NOTE: ideal batch size is one, because sentences are all of different length.\n # In other words, we have no option but to feed in sentences one by one into the model\n # and compute loss at the end.\n\n # TODO: what if the sentences in a batch are all of different lengths?\n # - should be have the longest sentence as 2nd dim?\n # - would zero endings work for other smaller sentences?\n\n y = torch.LongTensor(batch_size).type(torch.LongTensor)\n if self.cuda and torch.cuda.is_available():\n y = y.cuda()\n\n tensorized_inputs = []\n for i in range(len(batch_ques)):\n xq = Variable(self.make_input_matrix(batch_ques[i], word_vectors, vec_dim))\n xs = Variable(self.make_input_matrix(batch_sents[i], word_vectors, vec_dim))\n ext_feats = torch.FloatTensor(batch_ext_feats[i])\n if self.cuda and torch.cuda.is_available():\n ext_feats = ext_feats.cuda()\n ext_feats = Variable(ext_feats)\n ext_feats = torch.unsqueeze(ext_feats, 0)\n y[i] = batch_labels[i]\n tensorized_inputs.append((xq, xs, ext_feats))\n\n return tensorized_inputs, Variable(y)\n","sub_path":"sm_cnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"338220733","text":"class AbstractGroup(object):\n \"\"\"base class for containers of sprites\n\n AbstractGroup does everything needed to behave as a normal group. You can\n easily subclass a new group class from this or the other groups below if\n you want to add more features.\n\n Any AbstractGroup-derived sprite groups act like sequences and support\n iteration, len, and so on.\n\n \"\"\"\n\n # dummy val to identify sprite groups, and avoid infinite recursion\n _spritegroup = True\n\n def __init__(self):\n self.spritedict = {}\n self.lostsprites = []\n\n def sprites(self):\n \"\"\"get a list of sprites in the group\n\n Group.sprite(): return list\n\n Returns an object that can be looped over with a 'for' loop. (For now,\n it is always a list, but this could change in a future version of\n pygame.) Alternatively, you can get the same information by iterating\n directly over the sprite group, e.g. 'for sprite in group'.\n\n \"\"\"\n return list(self.spritedict)\n\n def add_internal(self, sprite):\n self.spritedict[sprite] = 0\n\n def remove_internal(self, sprite):\n r = self.spritedict[sprite]\n if r:\n self.lostsprites.append(r)\n del self.spritedict[sprite]\n\n def has_internal(self, sprite):\n return sprite in self.spritedict\n\n def copy(self):\n \"\"\"copy a group with all the same sprites\n\n Group.copy(): return Group\n\n Returns a copy of the group that is an instance of the same class\n and has the same sprites in it.\n\n \"\"\"\n return self.__class__(self.sprites())\n\n def __iter__(self):\n return iter(self.sprites())\n\n def __contains__(self, sprite):\n return self.has(sprite)\n\n def add(self, *sprites):\n \"\"\"add sprite(s) to group\n\n Group.add(sprite, list, group, ...): return None\n\n Adds a sprite or sequence of sprites to a group.\n\n \"\"\"\n for sprite in sprites:\n # It's possible that some sprite is also an iterator.\n # If this is the case, we should add the sprite itself,\n # and not the iterator object.\n if isinstance(sprite, Sprite):\n if not self.has_internal(sprite):\n self.add_internal(sprite)\n sprite.add_internal(self)\n else:\n try:\n # See if sprite is an iterator, like a list or sprite\n # group.\n self.add(*sprite)\n except (TypeError, AttributeError):\n # Not iterable. This is probably a sprite that is not an\n # instance of the Sprite class or is not an instance of a\n # subclass of the Sprite class. Alternately, it could be an\n # old-style sprite group.\n if hasattr(sprite, '_spritegroup'):\n for spr in sprite.sprites():\n if not self.has_internal(spr):\n self.add_internal(spr)\n spr.add_internal(self)\n elif not self.has_internal(sprite):\n self.add_internal(sprite)\n sprite.add_internal(self)\n\n def remove(self, *sprites):\n \"\"\"remove sprite(s) from group\n\n Group.remove(sprite, list, or group, ...): return None\n\n Removes a sprite or sequence of sprites from a group.\n\n \"\"\"\n # This function behaves essentially the same as Group.add. It first\n # tries to handle each argument as an instance of the Sprite class. If\n # that failes, then it tries to handle the argument as an iterable\n # object. If that failes, then it tries to handle the argument as an\n # old-style sprite group. Lastly, if that fails, it assumes that the\n # normal Sprite methods should be used.\n for sprite in sprites:\n if isinstance(sprite, Sprite):\n if self.has_internal(sprite):\n self.remove_internal(sprite)\n sprite.remove_internal(self)\n else:\n try:\n self.remove(*sprite)\n except (TypeError, AttributeError):\n if hasattr(sprite, '_spritegroup'):\n for spr in sprite.sprites():\n if self.has_internal(spr):\n self.remove_internal(spr)\n spr.remove_internal(self)\n elif self.has_internal(sprite):\n self.remove_internal(sprite)\n sprite.remove_internal(self)\n\n def has(self, *sprites):\n \"\"\"ask if group has a sprite or sprites\n\n Group.has(sprite or group, ...): return bool\n\n Returns True if the given sprite or sprites are contained in the\n group. Alternatively, you can get the same information using the\n 'in' operator, e.g. 'sprite in group', 'subgroup in group'.\n\n \"\"\"\n return_value = False\n\n for sprite in sprites:\n if isinstance(sprite, Sprite):\n # Check for Sprite instance's membership in this group\n if self.has_internal(sprite):\n return_value = True\n else:\n return False\n else:\n try:\n if self.has(*sprite):\n return_value = True\n else:\n return False\n except (TypeError, AttributeError):\n if hasattr(sprite, '_spritegroup'):\n for spr in sprite.sprites():\n if self.has_internal(spr):\n return_value = True\n else:\n return False\n else:\n if self.has_internal(sprite):\n return_value = True\n else:\n return False\n\n return return_value\n\n def update(self, *args):\n \"\"\"call the update method of every member sprite\n\n Group.update(*args): return None\n\n Calls the update method of every member sprite. All arguments that\n were passed to this method are passed to the Sprite update function.\n\n \"\"\"\n for s in self.sprites():\n s.update(*args)\n\n def draw(self, surface):\n \"\"\"draw all sprites onto the surface\n\n Group.draw(surface): return None\n\n Draws all of the member sprites onto the given surface.\n\n \"\"\"\n sprites = self.sprites()\n surface_blit = surface.blit\n for spr in sprites:\n self.spritedict[spr] = surface_blit(spr.image, spr.rect)\n self.lostsprites = []\n\n def clear(self, surface, bgd):\n \"\"\"erase the previous position of all sprites\n\n Group.clear(surface, bgd): return None\n\n Clears the area under every drawn sprite in the group. The bgd\n argument should be Surface which is the same dimensions as the\n screen surface. The bgd could also be a function which accepts\n the given surface and the area to be cleared as arguments.\n\n \"\"\"\n if callable(bgd):\n for r in self.lostsprites:\n bgd(surface, r)\n for r in self.spritedict.values():\n if r:\n bgd(surface, r)\n else:\n surface_blit = surface.blit\n for r in self.lostsprites:\n surface_blit(bgd, r, r)\n for r in self.spritedict.values():\n if r:\n surface_blit(bgd, r, r)\n\n def empty(self):\n \"\"\"remove all sprites\n\n Group.empty(): return None\n\n Removes all the sprites from the group.\n\n \"\"\"\n for s in self.sprites():\n self.remove_internal(s)\n s.remove_internal(self)\n\n def __nonzero__(self):\n return truth(self.sprites())\n\n def __len__(self):\n \"\"\"return number of sprites in group\n\n Group.len(group): return int\n\n Returns the number of sprites contained in the group.\n\n \"\"\"\n return len(self.sprites())\n\n def __repr__(self):\n return \"<%s(%d sprites)>\" % (self.__class__.__name__, len(self))\n\n\nclass Group(AbstractGroup):\n \"\"\"container class for many Sprites\n\n pygame.sprite.Group(*sprites): return Group\n\n A simple container for Sprite objects. This class can be subclassed to\n create containers with more specific behaviors. The constructor takes any\n number of Sprite arguments to add to the Group. The group supports the\n following standard Python operations:\n\n in test if a Sprite is contained\n len the number of Sprites contained\n bool test if any Sprites are contained\n iter iterate through all the Sprites\n\n The Sprites in the Group are not ordered, so the Sprites are drawn and\n iterated over in no particular order.\n\n \"\"\"\n\n def __init__(self, *sprites):\n AbstractGroup.__init__(self)\n self.add(*sprites)\n\n\nRenderPlain = Group\nRenderClear = Group\n","sub_path":"game/collision_test/pygame_legacy/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":9263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"92564254","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import cohen_kappa_score, recall_score, precision_score, f1_score, accuracy_score, confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nfrom xgboost import XGBClassifier\nle = preprocessing.LabelEncoder()\n\ndata_dir = '/home/pramod/pramod_work/pdc_hackathon/data/pdc_ml_hackathon_2019-master/data/'\ntrain_data = pd.read_json(data_dir+'train.json', encoding='ascii')\ntrain_data.to_csv(data_dir+'train.csv', index=False)\nvalidation_data = pd.read_json(data_dir+'validation.json', encoding='ascii')\nvalidation_data.to_csv(data_dir+'validation.csv', index=False)\ntrain_data = pd.read_csv(data_dir+\"train.csv\")\ntrain_y1 = train_data.petition_category\ntrain_y2 = train_data.petition_is_victory\ndel train_data['petition_category']\ndel train_data['petition_is_victory']\nclf = RandomForestClassifier(max_depth=2, random_state=21)\ntrain_y1 = le.fit_transform(train_y1)\ntrain_y2 = le.fit_transform(train_y2)\n#initially tring for some of features following taking each feature at a time\ntrain_data[[\"_score\",\"petition_calculated_goal\",\"petition_displayed_signature_count\",\"petition_progress\",\"petition_total_signature_count\",\"petition_weekly_signature_count\",\"petition_primary_target_is_person\",\"petition_primary_target_publicly_visible\",\"petition_primary_target_type\",\"_source_coachable\",\"_source_discoverable\",\"_source_sponsored_campaign\"]]\nclf = LogisticRegression(random_state= 21)\ncolumns = []\naccuracy = []\ntrain_y = train_y2\nc=0\nfor col in train_x.columns:\n print(col)\n columns.append(col)\n train_x1 = train_x[col]\n if(c<5):\n if((any(train_x1.isnull()))|(any(train_x1.isna()))):\n train_x1[np.where(train_x1=='None')[0]] = (pd.DataFrame(train_x1)).median().iloc[0,0]\n if(c>5):\n if(train_x1.dtype!='bool'):\n if(any(train_x1=='None')):\n train_x1[np.where(train_x1=='None')[0]] = (pd.DataFrame(train_x1)).mode().iloc[0,0]\n X_train, X_test, y_train, y_test = train_test_split(train_x1, train_y, test_size=0.33, random_state=42)\n X_train = X_train.reshape(-1,1)\n X_test = X_test.reshape(-1,1)\n model= clf.fit(X_train,y_train)\n y_pred = model.predict(X_test)\n print(f1_score(y_test, y_pred))\n accuracy.append(f1_score(y_test,y_pred))\n c=c+1\n\n########undersampling majority class examples to deal with data imbalance########\nindices = np.concatenate([random.sample(np.where(train_y2==0)[0],len(np.where(train_y2==1)[0])),np.where(train_y2==1)[0]])\npd.DataFrame(indices).to_csv(data_dir+\"indices_usedafterUnderSampling.csv\")\ntrain_data_undersampled = train_data.iloc[indices,:]\n#,\"petition_primary_target_type\",\"petition_user_country_code\"\ntrain_y2_undersampled = train_y2[indices]\ntrain_x = train_data_undersampled[[\"_score\",\"petition_calculated_goal\",\"petition_displayed_signature_count\",\"petition_progress\",\"petition_total_signature_count\",\"petition_weekly_signature_count\",\"petition_primary_target_is_person\",\"petition_primary_target_publicly_visible\",\"_source_coachable\",\"petition_primary_target_type\",]]\n#clf = LogisticRegression(random_state= 21)\ncolumns = []\naccuracy = []\ntrain_y = train_y2_undersampled\nc=0\ntrain_data_undersampled_preprocessed = pd.DataFrame()\nfor col in train_x.columns:\n print(col)\n columns.append(col)\n train_x1 = train_x[col]\n if(c<5):\n if((any(train_x1.isnull()))|(any(train_x1.isna()))):\n train_x1[np.where(train_x1=='None')[0]] = (pd.DataFrame(train_x1)).median().iloc[0,0]\n if(c>5):\n if(train_x1.dtype!='bool'):\n if(any(train_x1=='None')):\n train_x1[np.where(train_x1=='None')[0]] = (pd.DataFrame(train_x1)).mode().iloc[0,0]\n if(col==\"petition_primary_target_type\"):\n train_x1 = le.fit_transform(train_x1)\n X_train, X_test, y_train, y_test = train_test_split(train_x1, train_y, test_size=0.33, random_state=42)\n X_train = X_train.reshape(-1,1)\n X_test = X_test.reshape(-1,1)\n model= clf.fit(X_train,y_train)\n y_pred = model.predict(X_test)\n print(f1_score(y_test, y_pred))\n accuracy.append(f1_score(y_test,y_pred))\n c=c+1\n train_data_undersampled_preprocessed = pd.concat([train_data_undersampled_preprocessed,train_x1],axis=1)\ntrain_data_undersampled_preprocessed = pd.concat([train_data_undersampled_preprocessed,train_y2_undersampled],axis=1)\ntrain_data_undersampled_preprocessed.to_csv(data_dir +\"train_data_undersampled_preprocessed_8.csv\")\npd.DataFrame(train_x1).to_csv(data_dir+\"undersampled_preprocessed_9thFeature.csv\")\n\n#overall results\nclf = RandomForestClassifier(max_depth=2, random_state=21)\ntrain_data_undersampled_preprocessed = pd.read_csv(data_dir+\"train_data_undersampled_preprocessed_8.csv\")\ntrain_y = train_data_undersampled_preprocessed.petition_is_victory\ndel train_data_undersampled_preprocessed['petition_is_victory']\ntrain_x = train_data_undersampled_preprocessed\nX_train, X_test, y_train, y_test = train_test_split(train_x, train_y, test_size=0.33, random_state=42)\n#X_train = X_train.reshape(-1,1)\n#X_test = X_test.reshape(-1,1)\nmodel= clf.fit(X_train,y_train)\ny_pred = model.predict(X_test)\nprint(f1_score(y_test, y_pred))\nconfusion_matrix(y_test,y_pred)\naccuracy_score(y_test,y_pred)\nc=0\ntest_data = pd.read_csv(data_dir+\"validation.csv\")\ntest_data = test_data[[\"_score\",\"petition_calculated_goal\",\"petition_displayed_signature_count\",\"petition_progress\",\"petition_total_signature_count\",\"petition_weekly_signature_count\",\"petition_primary_target_publicly_visible\",\"_source_coachable\",\"petition_primary_target_type\",]]\ntest_data_prepro=pd.DataFrame()\nfor col in test_data.columns:\n print(col)\n test_x1 = test_data[col]\n if(c<5):\n if((any(test_x1.isnull()))|(any(test_x1.isna()))):\n train_x1[np.where(test_x1=='None')[0]] = (pd.DataFrame(test_x1)).median().iloc[0,0]\n if(c>5):\n if(test_x1.dtype!='bool'):\n if(any(test_x1=='None')):\n test_x1[np.where(test_x1=='None')[0]] = (pd.DataFrame(test_x1)).mode().iloc[0,0]\n if(col==\"petition_primary_target_type\"):\n test_x1 = le.fit_transform(test_x1)\n test_data_prepro = pd.concat([test_data_prepro,test_x1],axis=1)\n c=c+1\ntest_data_prepro.to_csv(data_dir+\"validation_prepro.csv\")\npd.DataFrame(test_x1).to_csv(data_dir+\"validation_9.csv\")\ntest_data_prepro = pd.read_csv(data_dir+\"validation_prepro.csv\")\ntest_data_prepro.columns = X_test.columns\ny_pred = model.predict(test_data_prepro)\npd.DataFrame(y_pred).to_csv(data_dir+\"outputclass.csv\")\n","sub_path":"code/isvictory_final_approach.py","file_name":"isvictory_final_approach.py","file_ext":"py","file_size_in_byte":6718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"164753183","text":"#!/usr/bin/python3\nimport re\nfrom nltk import pos_tag\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.util import bigrams\nimport sys\nimport getopt\nimport string\nimport os\nimport csv\nimport _pickle as pickle\nimport math\nfrom queue import PriorityQueue\nfrom utility import tokenize, is_valid\n\npunc = string.punctuation\nblock_count = 0 # running count of the number of blocks\nmax_len = 0\nBLOCKS = \"blocks\"\nDICTIONARY = {} # stores (key, value) as (doc_id, doc_len)\nRELEVANT = {}\nREL_TAGS = ['JJ', 'JJR', 'JJS', 'NN', 'NNS', 'NNP', 'NNPS', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']\n\ndef usage():\n print(\"usage: \" + sys.argv[0] + \" -i directory-of-documents -d dictionary-file -p postings-file\")\n\n\ndef build_index(in_dir, out_dict, out_postings):\n '''\n Builds index from documents stored in the input directory,\n then output the dictionary file and postings file\n '''\n print('indexing...')\n # This is an empty method\n # Pls implement your code in below\n csv.field_size_limit(sys.maxsize)\n limit = 20\n os.makedirs(BLOCKS, exist_ok=True)\n\n with open(in_dir, 'r+', encoding=\"utf-8\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n doc_list = list(csv_reader)\n doc_list = doc_list[1:] # ignore header line\n doc_chunks = [doc_list[i * limit:(i + 1) * limit] for i in range((len(doc_list) + limit - 1) // limit)]\n for chunk in doc_chunks:\n spimi_invert(chunk)\n f = open(out_dict, 'w+', encoding=\"utf-8\")\n f.close()\n f = open(out_postings, 'w+', encoding=\"utf-8\")\n f.close()\n offset = record_doc_length(out_dict, out_postings)\n merge(BLOCKS, out_dict, out_postings)\n write_rel_to_disk()\n\n\ndef record_doc_length(out_dict, out_postings):\n '''\n Records docIDs and their respective normalised doc lengths\n '''\n global DICTIONARY\n result = ''\n\n accum = 0 # for gap encoding\n for doc_id, doc_len in sorted(DICTIONARY.items()):\n gap = doc_id - accum\n result += str(gap) + '-' + str(doc_len) + ' '\n accum += gap\n\n # (doc_frequency, absolute_offset, accumulative_offset)\n dict_expr = \"* 0 \" + str(len(result)) + \"\\n\"\n\n write_to_file(out_dict, dict_expr)\n write_to_file(out_postings, result)\n\n\ndef write_to_file(file, content):\n '''\n Writes out lines to disk for search phase later\n '''\n fw = open(file, 'a', encoding=\"utf-8\")\n fw.write(''.join(content))\n fw.close()\n\n\ndef spimi_invert(chunk):\n '''\n Executes SPIMI Invert algorithm for each chunk of documents\n For each chunk, store a master index\n For each entry in the chunk, collect term frequencies and calculate the weights (for normalised doc length)\n Add [doc id, term freq] to the master index and log the normalised document length\n '''\n global block_count, DICTIONARY\n print('block:', block_count)\n index = {} # index for the whole chunk\n\n for entry in chunk:\n entry_index = {}\n doc_id, title, content, date, court = entry[0], entry[1], entry[2], entry[3], entry[4]\n\n # process title words\n title_words = []\n gen_unigram(entry_index, doc_id, title.rstrip(), title_words, 0)\n gen_bigram(entry_index, doc_id, title_words, 0)\n\n # process content words\n content_words = []\n for sent in sent_tokenize(content): # content\n gen_unigram(entry_index, doc_id, sent, content_words, 1)\n gen_bigram(entry_index, doc_id, content_words, 1)\n\n # process dates\n gen_unigram(entry_index, doc_id, date.rstrip(), [], 2)\n\n # process court words\n court_words = []\n gen_unigram(entry_index, doc_id, court.rstrip(), court_words, 3)\n gen_bigram(entry_index, doc_id, court_words, 3)\n\n doc_len = 0\n for token, posting_list in entry_index.items():\n doc_len += (1 + math.log10(posting_list[1]))**2\n if token not in index:\n index[token] = [posting_list]\n else:\n curr_posting = index[token]\n curr_posting.append(posting_list)\n index[token] = curr_posting\n DICTIONARY[int(doc_id)] = float(\"{:.2f}\".format(math.sqrt(doc_len)))\n trim_rel_dict_entry(doc_id, entry_index)\n block_count += 1\n output_file = \"block\" + str(block_count) + \".txt\"\n write_block_to_disk(index, output_file)\n\n\ndef gen_unigram(entry_index, doc_id, section_content, section_words, zone_index):\n '''\n Generates unigrams based on given text\n '''\n rel_words = []\n for word in word_tokenize(section_content):\n if is_valid(word):\n tagged_word = pos_tag([word])\n tag = tagged_word[0][1]\n tokenized = tokenize(word)\n if tag in REL_TAGS and tokenized not in rel_words:\n rel_words.append(tokenized)\n section_words.append(tokenized)\n if tokenized not in entry_index:\n zones = [0, 0, 0, 0]\n zones[zone_index] += 1 # add title zone\n entry_index[tokenized] = [int(doc_id), 1, zones]\n else:\n curr_count = entry_index[tokenized][1]\n zones = entry_index[tokenized][2]\n zones[zone_index] += 1\n entry_index[tokenized] = [int(doc_id), curr_count + 1, zones]\n # Adding relevant terms to relevant dictionary\n if doc_id not in RELEVANT:\n RELEVANT[doc_id] = rel_words\n else:\n existing_rel_word = RELEVANT[doc_id]\n for word in rel_words:\n if word not in existing_rel_word:\n existing_rel_word.append(word)\n RELEVANT[doc_id] = existing_rel_word\n\n\ndef gen_bigram(entry_index, doc_id, section_words, zone_index):\n '''\n Generates bigrams based on given text\n '''\n for entry in list(bigrams(section_words)):\n if is_valid(entry[0]) and is_valid(entry[1]):\n bigram = tokenize(entry[0]) + \"_\" + tokenize(entry[1])\n if bigram not in entry_index:\n zones = [0, 0, 0, 0]\n zones[zone_index] += 1\n entry_index[bigram] = [int(doc_id), 1, zones]\n else:\n curr_count = entry_index[bigram][1]\n zones = entry_index[bigram][2]\n zones[zone_index] += 1\n entry_index[bigram] = [int(doc_id), curr_count + 1, zones]\n\n\ndef trim_rel_dict_entry(doc_id, entry_index):\n '''\n Trims the relevant terms for the given document to the top 5\n '''\n terms = RELEVANT[doc_id]\n\n num_terms = len(terms)\n\n # use tf calculation to rank the terms\n tf_scores = {}\n for term in terms:\n # example of entry_index entry: 'court': [246407, 3, [0, 2, 0, 1]]\n term_freq = entry_index[term][1]\n tf_scores[term] = 1 + math.log(term_freq, 10)\n \n tf_scores.update((term, score / num_terms) for term, score in tf_scores.items())\n\n # sort tf_scores from highest to lowest\n sorted_tf_scores = dict(sorted(tf_scores.items(), key=lambda item: item[1], reverse=True))\n\n # trim relevant dictionary entry to top 5 scoring items\n RELEVANT[doc_id] = list(sorted_tf_scores.keys())[:5]\n\n\ndef write_block_to_disk(index, output_file):\n '''\n Writes out a block to disk in /blocks folder\n '''\n global max_len\n index_items = index.items()\n max_len = max(max_len, len(index_items))\n for key, value in index_items: # sorting each postings list\n value.sort() # sort by doc_id\n index_items = sorted(index_items) # sort terms\n output = open(os.path.join(BLOCKS, output_file), 'wb')\n for item in index_items:\n pickle.dump(item, output)\n output.close()\n\n\ndef write_rel_to_disk():\n '''\n Writes the dictionary of relevant terms for each document to disk\n '''\n rel_items = RELEVANT.items()\n output = open('rel.txt', 'wb')\n for item in rel_items:\n pickle.dump(item, output)\n output.close()\n\n\ndef merge(in_dir, out_dict, out_postings):\n '''\n Performs n-way merge, reading limit-number of entries from each block at a time\n '''\n print(\"merge\")\n global max_len\n limit = 5\n opened_files = {}\n removed_files = []\n\n # open all files and store in list\n for entry in os.listdir(in_dir):\n opened_files[entry] = open(os.path.join(in_dir, entry), 'rb')\n\n # initialising PQ\n pq = PriorityQueue()\n for i in range(limit):\n for block_name, file_read in opened_files.items():\n if block_name not in removed_files:\n try:\n temp_item = list(pickle.load(file_read))\n # block where the item of (term, docID) is from\n temp_item.append(block_name)\n pq.put(temp_item)\n except EOFError as error:\n removed_files.append(block_name)\n\n term_to_write = ''\n posting_list_to_write = []\n\n while not pq.empty():\n item = pq.get()\n term, posting_list, block_name = item[0], item[1], item[2]\n if term_to_write == '': # first term we are processing\n term_to_write = term\n posting_list_to_write = posting_list\n elif term_to_write != term: # time to write our current term to to disk because we encountered a new term\n posting_list_to_write.sort()\n posting_list_to_write = gap_encoding(posting_list_to_write)\n posting_list_str = posting_to_str(posting_list_to_write)\n\n # (doc_frequency, absolute_offset, accumulative_offset)\n\n\n dict_entry = term_to_write + \" \" + str(len(posting_list_to_write)) + \" \" + str(len(posting_list_str)) + \"\\n\"\n write_to_file(out_dict, dict_entry)\n write_to_file(out_postings, posting_list_str)\n \n # resetting variables for new term\n term_to_write = term\n posting_list_to_write = posting_list\n else: # curr_term == term\n posting_list_to_write.extend(posting_list)\n\n if block_name not in removed_files:\n try:\n unpickler = pickle.Unpickler(opened_files[block_name])\n temp_item = list(unpickler.load())\n # block where the item of (term, docID) is from\n temp_item.append(block_name)\n pq.put(temp_item)\n except EOFError as error:\n removed_files.append(block_name)\n\n\ndef gap_encoding(posting_list):\n '''\n Compresses posting list by adopting gap encoding for doc-IDs\n Example input: [[247336, 1, [0, 1, 0, 0]], [247336, 1, [0, 1, 0, 0]], [2140544, 1, [0, 1, 0, 0]]]\n '''\n final_posting = []\n accum = 0\n for posting in posting_list:\n doc_id = posting[0]\n gap = doc_id - accum\n final_posting.append([gap, posting[1], posting[2]])\n accum += gap\n return final_posting\n\n\ndef posting_to_str(posting_list):\n '''\n Converts a posting list to string form of docID-termFreq-zones\n '''\n result = ''\n for posting in posting_list:\n separator = ''\n zones_lst = posting[2]\n zones_str = ''\n for i in range(len(zones_lst) - 1):\n if i == len(zones_lst) - 1:\n if zones_lst[i] != 0:\n zones_str = separator.join([zones_str, str(zones_lst[i])])\n if zones_lst[i] == 0:\n zones_str = separator.join([zones_str, ','])\n else:\n zones_str = separator.join([zones_str, str(zones_lst[i]) ,','])\n result = separator.join([result, str(posting[0]), '-', zones_str, ' '])\n return result\n\ninput_directory = output_file_dictionary = output_file_postings = None\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:')\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor o, a in opts:\n if o == '-i': # input directory\n input_directory = a\n elif o == '-d': # dictionary file\n output_file_dictionary = a\n elif o == '-p': # postings file\n output_file_postings = a\n else:\n assert False, \"unhandled option\"\n\nif input_directory == None or output_file_postings == None or output_file_dictionary == None:\n usage()\n sys.exit(2)\n\nbuild_index(input_directory, output_file_dictionary, output_file_postings)\n","sub_path":"HW4/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":12245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"404658360","text":"import matplotlib.pyplot as plt\n\nf = open(\"./wrench_y_list.txt\",\"r\")\nlist_row = []\n\nfor x in f:\n list_row.append(float(x.rstrip(\"\\n\")))\nf.close()\n\ny = list_row\nx = range(1,len(y)+1)\n\nprint(y)\nprint(x)\n\nplt.plot(x, y)\nplt.show()\n\n","sub_path":"vegs_recognition/scripts/list_to_graph_y.py","file_name":"list_to_graph_y.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"603861863","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom constants import const\nimport h5py\nimport sys\n\n\ndef pltmap(H, pcA, pcB):\n\n C = const()\n\n fig = plt.figure(figsize=[7.5, 5])\n\n \"\"\"define the colors of interest\"\"\"\n n_col = len(C['set_id_cal'] + C['set_id_val'])\n colormat = cm.rainbow(np.linspace(0, 1, n_col))\n gray = [.7, .7, .7]\n\n f_red = h5py.File(\"spatial_reduced_L%s.hdf5\" % H, 'r')\n\n \"\"\"plot SVE sets for cal\"\"\"\n\n c = 0\n\n for ii in xrange(len(C['set_id_cal'])):\n\n set_id = C['set_id_cal'][ii]\n\n reduced = f_red.get('reduced_%s' % set_id)[...]\n meanA = reduced[:, pcA].mean()\n meanB = reduced[:, pcB].mean()\n\n plt.text(meanA, meanB+4, C['names_cal'][ii],\n horizontalalignment='center',\n verticalalignment='center')\n\n plt.plot(reduced[:, pcA], reduced[:, pcB],\n marker='s', markersize=6, color=colormat[c, :],\n alpha=0.4, linestyle='')\n plt.plot(meanA, meanB,\n marker='s', markersize=8, color=colormat[c, :],\n linestyle='')\n\n # varmat = np.var(reduced, axis=0)\n # msg = \"total variance for %s: %s\" % (set_id, varmat.sum())\n # rr.WP(msg, C['wrt_file'])\n\n c += 1\n\n \"\"\"plot SVE sets for val\"\"\"\n\n for ii in xrange(len(C['set_id_val'])):\n\n set_id = C['set_id_val'][ii]\n\n reduced = f_red.get('reduced_%s' % set_id)[...]\n meanA = reduced[:, pcA].mean()\n meanB = reduced[:, pcB].mean()\n\n plt.text(meanA, meanB+4, C['names_val'][ii],\n horizontalalignment='center',\n verticalalignment='center')\n\n # plt.text(txtm[ii, 0], txtm[ii, 1], C['names_val'][ii],\n # horizontalalignment='center',\n # verticalalignment='center')\n\n plt.plot(reduced[:, pcA], reduced[:, pcB],\n marker='o', markersize=6, color=colormat[c, :],\n alpha=0.4, linestyle='')\n plt.plot(meanA, meanB,\n marker='o', markersize=8, color=colormat[c, :],\n linestyle='')\n\n # varmat = np.var(reduced, axis=0)\n # msg = \"total variance for %s: %s\" % (set_id, varmat.sum())\n # rr.WP(msg, C['wrt_file'])\n\n c += 1\n\n plt.margins(.2)\n\n plt.xlabel(\"PC%s\" % str(pcA+1))\n plt.ylabel(\"PC%s\" % str(pcB+1))\n\n plt.grid(linestyle='-', alpha=0.15)\n\n \"\"\"create a legend based on points not plotted\"\"\"\n p1 = plt.plot(0, 0, marker='s', markersize=6,\n color=gray, linestyle='', label='calibration')\n p2 = plt.plot(0, 0, marker='o', markersize=6,\n color=gray, linestyle='', label='validation')\n plt.legend(loc='upper left', shadow=True, fontsize='medium', ncol=2)\n p1[0].remove()\n p2[0].remove()\n\n fig.tight_layout()\n\n # plt.legend(bbox_to_anchor=(1.02, 1), loc=2, shadow=True, fontsize='medium')\n # fig.tight_layout(rect=(0, 0, .7, 1))\n\n f_red.close()\n\n fig_name = 'pc%s_pc%s_L%s.png' % (pcA+1, pcB+1, H)\n fig.canvas.set_window_title(fig_name)\n plt.savefig(fig_name)\n\n\nif __name__ == '__main__':\n H = np.int64(sys.argv[1])\n pcA = np.int64(sys.argv[2])\n pcB = np.int64(sys.argv[3])\n\n pltmap(H, pcA, pcB)\n\n plt.show()\n","sub_path":"fip_collab/2016_08_11_polycrystal_FIP/plot_pc_map.py","file_name":"plot_pc_map.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"216191829","text":"import os\nimport sys\nimport time\n# Use the built-in version of scandir/stat if possible, otherwise\n# use the scandir module version\ntry:\n from os import scandir, stat # noqa # pylint: disable=unused-import\nexcept ImportError:\n from scandir import scandir, stat # noqa # pylint: disable=unused-import\n\nfrom graphite.intervals import Interval, IntervalSet\nfrom graphite.carbonlink import CarbonLink\nfrom graphite.logger import log\nfrom django.conf import settings\n\ntry:\n import whisper\nexcept ImportError:\n whisper = False\n\n# The parser was repalcing __readHeader with the __readHeader\n# which was not working.\nif bool(whisper):\n whisper__readHeader = whisper.__readHeader\n\ntry:\n import ceres\nexcept ImportError:\n ceres = False\n\ntry:\n import rrdtool\nexcept ImportError:\n rrdtool = False\n\ntry:\n import gzip\nexcept ImportError:\n gzip = False\n\n\nclass FetchInProgress(object):\n def __init__(self, wait_callback):\n self.wait_callback = wait_callback\n\n def waitForResults(self):\n return self.wait_callback()\n\n\nclass MultiReader(object):\n __slots__ = ('nodes',)\n\n def __init__(self, nodes):\n self.nodes = nodes\n\n def get_intervals(self):\n interval_sets = []\n for node in self.nodes:\n interval_sets.extend( node.intervals.intervals )\n return IntervalSet( sorted(interval_sets) )\n\n def fetch(self, startTime, endTime, now=None, requestContext=None):\n # Start the fetch on each node\n fetches = []\n\n for n in self.nodes:\n try:\n fetches.append(n.fetch(startTime, endTime, now, requestContext))\n except:\n log.exception(\"Failed to initiate subfetch for %s\" % str(n))\n\n def merge_results():\n results = {}\n\n # Wait for any asynchronous operations to complete\n for i, result in enumerate(fetches):\n if isinstance(result, FetchInProgress):\n try:\n results[i] = result.waitForResults()\n except:\n log.exception(\"Failed to complete subfetch\")\n results[i] = None\n\n results = [r for r in results.values() if r is not None]\n if not results:\n raise Exception(\"All sub-fetches failed\")\n\n return reduce(self.merge, results)\n\n return FetchInProgress(merge_results)\n\n def merge(self, results1, results2):\n # Ensure results1 is finer than results2\n if results1[0][2] > results2[0][2]:\n results1, results2 = results2, results1\n\n time_info1, values1 = results1\n time_info2, values2 = results2\n start1, end1, step1 = time_info1\n start2, end2, step2 = time_info2\n\n step = step1 # finest step\n start = min(start1, start2) # earliest start\n end = max(end1, end2) # latest end\n time_info = (start, end, step)\n values = []\n\n t = start\n while t < end:\n # Look for the finer precision value first if available\n i1 = (t - start1) / step1\n\n if len(values1) > i1:\n v1 = values1[i1]\n else:\n v1 = None\n\n if v1 is None:\n i2 = (t - start2) / step2\n\n if len(values2) > i2:\n v2 = values2[i2]\n else:\n v2 = None\n\n values.append(v2)\n else:\n values.append(v1)\n\n t += step\n\n return (time_info, values)\n\n\nclass CeresReader(object):\n __slots__ = ('ceres_node', 'real_metric_path')\n supported = bool(ceres)\n\n def __init__(self, ceres_node, real_metric_path):\n self.ceres_node = ceres_node\n self.real_metric_path = real_metric_path\n\n def get_intervals(self):\n intervals = []\n for info in self.ceres_node.slice_info:\n (start, end, step) = info\n intervals.append( Interval(start, end) )\n\n return IntervalSet(intervals)\n\n def fetch(self, startTime, endTime):\n data = self.ceres_node.read(startTime, endTime)\n time_info = (data.startTime, data.endTime, data.timeStep)\n values = list(data.values)\n\n # Merge in data from carbon's cache\n try:\n cached_datapoints = CarbonLink.query(self.real_metric_path)\n except:\n log.exception(\"Failed CarbonLink query '%s'\" % self.real_metric_path)\n cached_datapoints = []\n\n values = merge_with_cache(cached_datapoints,\n data.startTime,\n data.timeStep,\n values)\n\n return time_info, values\n\n\nclass WhisperReader(object):\n __slots__ = ('fs_path', 'real_metric_path')\n supported = bool(whisper)\n\n def __init__(self, fs_path, real_metric_path):\n self.fs_path = fs_path\n self.real_metric_path = real_metric_path\n\n def get_intervals(self):\n start = time.time() - whisper.info(self.fs_path)['maxRetention']\n end = max( stat(self.fs_path).st_mtime, start )\n return IntervalSet( [Interval(start, end)] )\n\n def fetch(self, startTime, endTime, now=None, requestContext=None):\n try:\n data = whisper.fetch(self.fs_path, startTime, endTime, now)\n except IOError:\n log.exception(\"Failed fetch of whisper file '%s'\" % self.fs_path)\n return None\n if not data:\n return None\n\n time_info, values = data\n (start,end,step) = time_info\n\n meta_info = whisper.info(self.fs_path)\n aggregation_method = meta_info['aggregationMethod']\n # Merge in data from carbon's cache\n cached_datapoints = []\n try:\n cached_datapoints = CarbonLink.query(self.real_metric_path)\n except:\n log.exception(\"Failed CarbonLink query '%s'\" % self.real_metric_path)\n cached_datapoints = []\n\n if isinstance(cached_datapoints, dict):\n cached_datapoints = cached_datapoints.items()\n\n values = merge_with_cache(cached_datapoints,\n start,\n step,\n values,\n aggregation_method)\n\n return time_info, values\n\n\nclass CarbonCacheReader(object):\n __slots__ = ('metric')\n supported = True\n\n def __init__(self, metric):\n self.metric = metric\n\n def get_intervals(self):\n # intervals doesn't matter in such type of reader\n # Let's return time.time()\n start = time.time()\n end = start\n return IntervalSet( [Interval(start, end)] )\n\n def _format_and_extract_time(self, start_time, end_time, max_retention):\n \"\"\"\n This function is design for formatting and extracting from\n and until time.\n \"\"\"\n now = int(time.time())\n oldest_time = now - max_retention\n\n # Some checks\n if end_time is None:\n end_time = now\n if start_time is None:\n return None\n\n from_time = int(start_time)\n until_time = int(end_time)\n\n # Compare with now\n if from_time > now:\n return None\n if until_time > now:\n until_time = now\n\n # Compare with oldest_time\n if from_time < oldest_time:\n from_time = oldest_time\n if until_time < oldest_time:\n return None\n\n return (from_time, until_time)\n\n def _calculate_step(self, archives, diff):\n target_arch = None\n for archive in archives:\n retention = archive[0] * archive[1]\n if retention >= diff:\n target_arch = archive\n break\n if not target_arch:\n return None\n step = target_arch[0]\n return step\n\n def _query_and_format_cache_data(self, from_time, until_time, step):\n cached_results = CarbonLink.query(self.metric)\n if cached_results:\n from_interval = int(from_time - (from_time % step)) + step\n until_interval = int(until_time - (until_time % step)) + step\n if from_interval == until_interval:\n until_interval += step\n points = (until_interval - from_interval) // step\n values = [None] * points\n time_info = (from_interval, until_interval, step)\n for (timestamp, value) in cached_results:\n interval = int(timestamp - (timestamp % step))\n index = (interval - from_interval) / step\n if index < 0 or index >= points:\n continue\n values[index] = value\n return time_info, values\n\n def fetch(self, start_time, end_time):\n # Fetch data from carbon cache through CarbonLink\n schema = CarbonLink.get_storage_schema(self.metric)\n archives = schema[\"archives\"]\n # Get lowest step\n lowest_step = min([arch[0] for arch in archives])\n\n now = int(time.time())\n max_retention = max([arch[0] * arch[1] for arch in archives])\n oldest_time = now - max_retention\n\n # format and extract from/until time\n from_and_until_time = self._format_and_extract_time(start_time, end_time, max_retention)\n if not from_and_until_time:\n return None\n from_time, until_time = from_and_until_time\n\n # calcucate step\n diff = now - from_time\n # sorted_archives = sorted(archives, key=lambda x: x[0] * x[1])\n step = self._calculate_step(archives, diff)\n if not step:\n return None\n\n # Only check carbon-cache if step == lowest_step\n if step == lowest_step:\n return self._query_and_format_cache_data(from_time, until_time, step)\n return None\n\n\nclass GzippedWhisperReader(WhisperReader):\n supported = bool(whisper and gzip)\n\n def get_intervals(self):\n fh = gzip.GzipFile(self.fs_path, 'rb')\n try:\n info = whisper__readHeader(fh) # evil, but necessary.\n finally:\n fh.close()\n\n start = time.time() - info['maxRetention']\n end = max( stat(self.fs_path).st_mtime, start )\n return IntervalSet( [Interval(start, end)] )\n\n def fetch(self, startTime, endTime):\n fh = gzip.GzipFile(self.fs_path, 'rb')\n try:\n return whisper.file_fetch(fh, startTime, endTime)\n finally:\n fh.close()\n\n\nclass RRDReader:\n supported = bool(rrdtool)\n\n @staticmethod\n def _convert_fs_path(fs_path):\n if isinstance(fs_path, unicode):\n fs_path = fs_path.encode(sys.getfilesystemencoding())\n return os.path.realpath(fs_path)\n\n def __init__(self, fs_path, datasource_name):\n self.fs_path = RRDReader._convert_fs_path(fs_path)\n self.datasource_name = datasource_name\n\n def get_intervals(self):\n start = time.time() - self.get_retention(self.fs_path)\n end = max( stat(self.fs_path).st_mtime, start )\n return IntervalSet( [Interval(start, end)] )\n\n def fetch(self, startTime, endTime):\n startString = time.strftime(\"%H:%M_%Y%m%d+%Ss\", time.localtime(startTime))\n endString = time.strftime(\"%H:%M_%Y%m%d+%Ss\", time.localtime(endTime))\n\n if settings.FLUSHRRDCACHED:\n rrdtool.flushcached(self.fs_path, '--daemon', settings.FLUSHRRDCACHED)\n\n (timeInfo, columns, rows) = rrdtool.fetch(self.fs_path,settings.RRD_CF,'-s' + startString,'-e' + endString)\n colIndex = list(columns).index(self.datasource_name)\n rows.pop() #chop off the latest value because RRD returns crazy last values sometimes\n values = (row[colIndex] for row in rows)\n\n return (timeInfo, values)\n\n @staticmethod\n def get_datasources(fs_path):\n info = rrdtool.info(RRDReader._convert_fs_path(fs_path))\n\n if 'ds' in info:\n return [datasource_name for datasource_name in info['ds']]\n else:\n ds_keys = [ key for key in info if key.startswith('ds[') ]\n datasources = set( key[3:].split(']')[0] for key in ds_keys )\n return list(datasources)\n\n @staticmethod\n def get_retention(fs_path):\n info = rrdtool.info(RRDReader._convert_fs_path(fs_path))\n if 'rra' in info:\n rras = info['rra']\n else:\n # Ugh, I like the old python-rrdtool api better..\n rra_count = max([ int(key[4]) for key in info if key.startswith('rra[') ]) + 1\n rras = [{}] * rra_count\n for i in range(rra_count):\n rras[i]['pdp_per_row'] = info['rra[%d].pdp_per_row' % i]\n rras[i]['rows'] = info['rra[%d].rows' % i]\n\n retention_points = 0\n for rra in rras:\n points = rra['pdp_per_row'] * rra['rows']\n if points > retention_points:\n retention_points = points\n\n return retention_points * info['step']\n\n\ndef merge_with_cache(cached_datapoints, start, step, values, func=None):\n\n consolidated=[]\n\n # Similar to the function in render/datalib:TimeSeries\n def consolidate(func, values):\n usable = [v for v in values if v is not None]\n if not usable: return None\n if func == 'sum':\n return sum(usable)\n if func == 'average':\n return float(sum(usable)) / len(usable)\n if func == 'max':\n return max(usable)\n if func == 'min':\n return min(usable)\n if func == 'last':\n return usable[-1]\n raise Exception(\"Invalid consolidation function: '%s'\" % func)\n\n if func:\n consolidated_dict = {}\n for (timestamp, value) in cached_datapoints:\n interval = timestamp - (timestamp % step)\n if interval in consolidated_dict:\n consolidated_dict[interval].append(value)\n else:\n consolidated_dict[interval] = [value]\n for interval in consolidated_dict:\n value = consolidate(func, consolidated_dict[interval])\n consolidated.append((interval, value))\n\n else:\n consolidated = cached_datapoints\n\n for (interval, value) in consolidated:\n try:\n i = int(interval - start) / step\n if i < 0:\n # cached data point is earlier then the requested data point.\n # meaning we can definitely ignore the cache result.\n # note that we cannot rely on the 'except'\n # in this case since 'values[-n]='\n # is equivalent to 'values[len(values) - n]='\n continue\n values[i] = value\n except:\n pass\n\n return values\n","sub_path":"webapp/graphite/readers.py","file_name":"readers.py","file_ext":"py","file_size_in_byte":13379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"259486945","text":"import sys\nfrom PyQt4 import QtSql, QtCore, QtGui, uic\nfrom main_feedback_auto import * \nimport add_feedback_mod \nimport query_feedback_mod \nimport add_courses_mod \nimport query_courses_mod \nimport st_feedback_mod \nimport st_form_mod \nimport st_feedback_query_mod\nimport st_infoentry_mod\nimport st_modify_mod\nimport fee_infoentry_mod\nimport st_coursebatch_entry_mod\nimport st_coursebatch_modify_mod\n\nclass MainFeedback(QtGui.QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n self.setupUi(self)\n\n QtCore.QObject.connect(self.actionAddFeedback,QtCore.SIGNAL('triggered()'),self.AddFeedback)\n QtCore.QObject.connect(self.actionQueryFeedback,QtCore.SIGNAL('triggered()'),self.QueryFeedback)\n QtCore.QObject.connect(self.actionAddCourse,QtCore.SIGNAL('triggered()'),self.AddCourses)\n QtCore.QObject.connect(self.actionQueryCourse,QtCore.SIGNAL('triggered()'),self.QueryCourses)\n QtCore.QObject.connect(self.actionModify_Feedback,QtCore.SIGNAL('triggered()'),self.StudentFeedQuery)\n QtCore.QObject.connect(self.actionStudent_feedback,QtCore.SIGNAL('triggered()'),self.StudentFeedback)\n QtCore.QObject.connect(self.actionSt_Add,QtCore.SIGNAL('triggered()'),self.AddStudent)\n QtCore.QObject.connect(self.actionSt_Modify,QtCore.SIGNAL('triggered()'),self.ModStudent)\n QtCore.QObject.connect(self.actionAddBatch,QtCore.SIGNAL('triggered()'),self.AddBatch)\n QtCore.QObject.connect(self.actionModify_3,QtCore.SIGNAL('triggered()'),self.ModBatch)\n QtCore.QObject.connect(self.actionStudent_Fees,QtCore.SIGNAL('triggered()'),self.Fees)\n QtCore.QObject.connect(self.actionAdd_Student,QtCore.SIGNAL('triggered()'),self.AddStudent)\n QtCore.QObject.connect(self.actionCreate_Batch,QtCore.SIGNAL('triggered()'),self.AddBatch)\n QtCore.QObject.connect(self.actionFees,QtCore.SIGNAL('triggered()'),self.Fees) \n def AddFeedback(self):\n add = add_feedback_mod.AddFeedback(self)\n add.setFixedSize(add.size())\n add.show()\n\n def QueryFeedback(self):\n query = query_feedback_mod.QueryFeedback(self)\n query.setFixedSize(query.size())\n query.show()\n query.ui.pb_select.setEnabled(False)\n\n def AddCourses(self):\n add1 = add_courses_mod.AddCourses(self)\n add1.setFixedSize(add1.size())\n add1.show()\n\n def QueryCourses(self):\n query1 = query_courses_mod.QueryCourses(self)\n query1.setFixedSize(query1.size())\n query1.show()\n\n def StudentFeedback(self):\n st1 = st_feedback_mod.STFeed(self)\n st1.setFixedSize(st1.size())\n st1.show()\n\n def StudentFeedQuery(self):\n st2 = st_feedback_query_mod.STQuery(self)\n st2.setFixedSize(st2.size())\n st2.show()\n\n def AddStudent(self):\n #addst=st_infoentry_mod.STInfoEntry(self)\n addst=st_modify_mod.STModify('A',self)\n #addst.mode=\"A\"\n addst.setFixedSize(addst.size())\n addst.show()\n\n def ModStudent(self):\n modst=st_modify_mod.STModify(\"C\",self)\n #modst.mode=\"C\"\n modst.setFixedSize(modst.size())\n modst.show()\n\n def AddBatch(self):\n addb=st_coursebatch_entry_mod.STCourseBatch(self)\n addb.setFixedSize(addb.size())\n addb.show()\n\n def ModBatch(self):\n modb=st_coursebatch_modify_mod.STCourseBatch(self)\n modb.setFixedSize(modb.size())\n modb.show()\n\n def Fees(self):\n stfees=fee_infoentry_mod.FeesInfo(self)\n stfees.setFixedSize(stfees.size())\n stfees.show()\n \nif (__name__ == \"__main__\"): \n app = QtGui.QApplication(sys.argv)\n feed = MainFeedback(None)\n feed.show()\n feed.setFixedSize(feed.size())\n app.exec_()\n","sub_path":"Files/main_feedback_mod.py","file_name":"main_feedback_mod.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"330394226","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\nfrom drawnow import *\n\ndef makeFig():\n # Visualize the result\n plt.title(\"Monte Carlo Simulation\")\n plt.plot(fx_x, fx_y)\n plt.scatter(x_out, y_out, s=1, color='red')\n plt.scatter(x_in, y_in, s=1, color='blue')\n plt.axvline(x=0, color='black')\n plt.axhline(y=0, color='black')\n plt.xlim(-0.3, 1.3)\n plt.ylim(-0.3, 3.0)\n plt.grid()\n plt.text(0.3, 2.3, \"- n : {}\\n- Conditional : {}\\n- Monte Carlo : {}\\n- scipy : {}\".format(n, area_target, manual_solution, scipy_solution[0]))\n \n\n# Set the number of iteration, which means the sample size\n# If you want to get more accurate value, you should increase the number\niteration = 100000\nn = 0\ncnt = 0\n\n### Method 2: Monte Carlo Integration ###\nrandom_number = np.random.uniform(low = 0, high = 1, size = iteration)\nexp_x_square = np.exp(-np.square(random_number))\nmanual_solution = np.mean(exp_x_square)\n\n\n### Method 3: scipy ###\nscipy_solution = integrate.quad(lambda x : math.exp(-x**2), 0, 1)\n\n# Draw a function to distinguish the samples\nfx_x = np.arange(-0.3, 1.3, 1 / iteration)\nfx_y = np.exp(-np.square(fx_x))\n\n### Method 1: Conditional Probability(Ratio Area) ###\n# 1-1. Set a larger area. In this case, this is rectangular\nheight = 2\nwidth = 1\narea_rectangular = height * width\n\n# 1-2. Generate random sample points: (x, y)\nx_rand = np.random.rand(iteration)\ny_rand = np.random.rand(iteration) * height\nfx_rand = np.exp(-np.square(x_rand))\n\n# 1-3. Prepare to categorize the points which are inside or outside the function\nx_in = []\ny_in = []\nx_out = []\ny_out = []\n\n# 1-4. Compare all the samples based on the function\nfor i in range(iteration):\n if y_rand[i] <= fx_rand[i]:\n x_in.append(x_rand[i])\n y_in.append(y_rand[i])\n else:\n x_out.append(x_rand[i])\n y_out.append(y_rand[i])\n cnt += 1\n if cnt > 99:\n # 1-5. Obatin the ratio between the sample points\n ratio = len(y_in) / i\n\n # 1-6. Get a result indirectly\n area_target = ratio * area_rectangular\n drawnow(makeFig)\n n += cnt\n cnt = 0\n\n# Print the results to check the accuracy(or error)\nprint(\"Conditional : {}, Monte Carlo : {}, scipy : {}\".format(area_target, manual_solution, scipy_solution))\n\n# plt.show()","sub_path":"programming/python/Simulator/MC_integration.py","file_name":"MC_integration.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"72784959","text":"'''\nObject detection and tracking with OpenCV\n ==> Real Time tracking with Pan-Tilt servos and Stepper motors\n Pan-Tilt based on original tracking object code developed by Adrian Rosebrock\n Visit original post: https://www.pyimagesearch.com/2016/05/09/opencv-rpi-gpio-and-gpio-zero-on-the-raspberry-pi/\n Stepper motor based on Adafruit code developed by Simon Monk\n Visit original post: https://learn.adafruit.com/adafruits-raspberry-pi-lesson-10-stepper-motors/overview\nDeveloped by Tyler Schoeppner - tyler.schoeppner.com @ 7Oct2020 \n'''\n\n# import the necessary packages\nfrom __future__ import print_function\nfrom imutils.video import VideoStream\nimport argparse\nimport imutils\nimport time\nimport cv2\nimport os\nimport RPi.GPIO as GPIO\nos.system('sudo pigpiod')\nimport pigpio\nimport board\nimport busio as io\nimport adafruit_ht16k33.matrix\nfrom test_LEDmatrix import ledsoff, neutralexp, surpriseexp, joyexp, angerexp, tiredexp\n\n# setup for LED matrix\ni2c = io.I2C(board.SCL, board.SDA)\nmatrix = adafruit_ht16k33.matrix.Matrix16x8(i2c)\n\n# define Servos GPIOs\n#tiltServo = 17\n\n# turn on movement for the camera servo\n#pi = pigpio.pi()\n\n# setup wheel servo motors\n#GPIO.setmode(GPIO.BCM)\n#GPIO.setwarnings(False)\n#coil_A_1_pin = 4\n#coil_A_2_pin = 26\n#coil_B_1_pin = 23\n#coil_B_2_pin = 24\n\n#coil2_A_1_pin = 16\n#coil2_A_2_pin = 22\n#coil2_B_1_pin = 27\n#coil2_B_2_pin = 20\n\n#StepCount=8\n#Seq = [\n# [1,0,0,0],\n# [1,1,0,0],\n# [0,1,0,0],\n# [0,1,1,0],\n# [0,0,1,0],\n# [0,0,1,1],\n# [0,0,0,1],\n# [1,0,0,1]\n# ]\n\n# define wheel speed\n#delay = 8\n#speed = delay / 10000.0\n\n# setup the pins on the drive stepper motors\n# first stepper motor\n#GPIO.setup(coil_A_1_pin, GPIO.OUT)\n#GPIO.setup(coil_A_2_pin, GPIO.OUT)\n#GPIO.setup(coil_B_1_pin, GPIO.OUT)\n#GPIO.setup(coil_B_2_pin, GPIO.OUT)\n\n# second stepper motor\n#GPIO.setup(coil2_A_1_pin, GPIO.OUT)\n#GPIO.setup(coil2_A_2_pin, GPIO.OUT)\n#GPIO.setup(coil2_B_1_pin, GPIO.OUT)\n#GPIO.setup(coil2_B_2_pin, GPIO.OUT)\n \n#def setStepleft(w1, w2, w3, w4):\n# GPIO.output(coil_A_1_pin, w1)\n# GPIO.output(coil_A_2_pin, w2)\n# GPIO.output(coil_B_1_pin, w3)\n# GPIO.output(coil_B_2_pin, w4)\n \n#def setStepright(k1, k2, k3, k4):\n# GPIO.output(coil2_A_1_pin, k1)\n# GPIO.output(coil2_A_2_pin, k2)\n# GPIO.output(coil2_B_1_pin, k3)\n# GPIO.output(coil2_B_2_pin, k4)\n \n#def spinleft(speed, steps):\n# for i in range(steps):\n# for j in range(StepCount):\n# setStepright(Seq[j][0], Seq[j][1], Seq[j][2], Seq[j][3])\n# time.sleep(speed)\n# for j in reversed(range(StepCount)):\n# setStepleft(Seq[j][0], Seq[j][1], Seq[j][2], Seq[j][3])\n# time.sleep(speed)\n \n#def spinright(speed, steps):\n# for i in range(steps):\n# for j in range(StepCount):\n# setStepleft(Seq[j][0], Seq[j][1], Seq[j][2], Seq[j][3])\n# time.sleep(speed)\n# for j in reversed(range(StepCount)):\n# setStepright(Seq[j][0], Seq[j][1], Seq[j][2], Seq[j][3])\n# time.sleep(speed)\n \n# position servos to present object at center of the frame\n#def mapServoPosition (x, y):\n# global tiltAngle\n# global spinAngle\n# if (x < 100):\n# spinAngle = 50\n# spinleft(speed, spinAngle)\n# print(\"spinleft\")\n \n# if (x > 400):\n# spinAngle = 50\n# spinright(speed, spinAngle)\n# print(\"spinright\")\n \n# if (y < 110):\n# tiltAngle -= 33\n# if tiltAngle < 1100:\n# tiltAngle = 1100\n# pi.set_servo_pulsewidth(tiltServo, tiltAngle)\n \n# if (y > 200):\n# tiltAngle += 33\n# if tiltAngle > 2100:\n# tiltAngle = 2100\n# pi.set_servo_pulsewidth(tiltServo, tiltAngle)\n \n# initialize the video stream and allow the camera sensor to warmup\nprint(\"[INFO] waiting for camera to warmup...\")\nvs = VideoStream(0).start()\ntime.sleep(2.0)\n\n# define the lower and upper boundaries of the object\n# to be tracked in the HSV color space\ncolorLower = (70, 70, 25)\ncolorUpper = (174, 255, 255)\n\n# Initialize servos\n#tiltAngle = 1800\n#spinAngle = 0\n\n# positioning Tilt servos at initial position\n#pi.set_servo_pulsewidth(tiltServo, tiltAngle)\n\n# initial expression\n# possible exp: neutralexp, surpriseexp, joyexp, angerexp, tiredexp\n\ntiredexp()\ntime.sleep(5)\nsurpriseexp()\ntime.sleep(5)\nledsoff()\n\n#foundobject = False\n \n# loop over the frames from the video stream\nwhile True:\n # grab the next frame from the video stream, Invert 180o, resize the\n # frame, and convert it to the HSV color space\n frame = vs.read()\n frame = imutils.resize(frame, width=500)\n frame = imutils.rotate(frame, angle=180)\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # construct a mask for the object color, then perform\n # a series of dilations and erosions to remove any small\n # blobs left in the mask\n mask = cv2.inRange(hsv, colorLower, colorUpper)\n mask = cv2.erode(mask, None, iterations=2)\n mask = cv2.dilate(mask, None, iterations=2)\n\n # find contours in the mask and initialize the current\n # (x, y) center of the object\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n center = None\n\n # only proceed if at least one contour was found\n if len(cnts) > 0:\n # find the largest contour in the mask, then use\n # it to compute the minimum enclosing circle and\n # centroid\n c = max(cnts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n #foundobject = True\n\n # only proceed if the radius meets a minimum size\n if radius > 10:\n # draw the circle and centroid on the frame,\n # then update the list of tracked points\n cv2.circle(frame, (int(x), int(y)), int(radius),\n (0, 255, 255), 2)\n cv2.circle(frame, center, 5, (0, 0, 255), -1)\n #neutralexp()\n #print(center)\n \n # position Servo at center of circle\n #mapServoPosition(int(x), int(y))\n\n # show the frame to our screen\n cv2.imshow(\"Frame\", frame)\n \n # if [ESC] key is pressed, stop the loop\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n break\n\n# do a bit of cleanup\nprint(\"\\n [INFO] Exiting Program and cleanup stuff \\n\")\npi.set_servo_pulsewidth(tiltServo, 1800)\nmatrix.fill(0)\ncv2.destroyAllWindows()\nvs.stop()\n \n \n \n \n \n ","sub_path":"BB2brain.py","file_name":"BB2brain.py","file_ext":"py","file_size_in_byte":6580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"445899404","text":"import sqlite3\r\n\r\ndef connect():\r\n conn=sqlite3.connect(\"fooddata.db\")\r\n cur=conn.cursor()\r\n cur.execute(\"CREATE TABLE IF NOT EXISTS food1(itemid INTEGER PRIMARY KEY,itemname text,hotelname text,price integer,quantity integer,phoneno integer,address text)\")\r\n conn.commit()\r\n conn.close()\r\n\r\ndef insert(itemid, itemname, hotelname, price, quantity, phoneno, address):\r\n conn = sqlite3.connect(\"fooddata.db\")\r\n cur = conn.cursor()\r\n cur.execute(\"INSERT INTO food1 VALUES(?,?,?,?,?,?,?)\",(itemid, itemname, hotelname, price, quantity, phoneno, address))\r\n conn.commit()\r\n conn.close()\r\n\r\ndef update(itemid, itemname, hotelname, price, quantity,phoneno,address):\r\n conn = sqlite3.connect(\"fooddata.db\")\r\n cur = conn.cursor()\r\n cur.execute(\"UPDATE food1 SET itemname=?,hotelname=?,price=?,quantity=?,phoneno=?,address=? WHERE itemid=?\",(itemname, hotelname, price, quantity,phoneno,address,itemid))\r\n conn.commit()\r\n conn.close()\r\n\r\ndef delete(itemid):\r\n conn = sqlite3.connect(\"fooddata.db\")\r\n cur = conn.cursor()\r\n cur.execute(\"DELETE FROM food1 WHERE itemid=?\", (itemid,))\r\n conn.commit()\r\n conn.close()\r\n\r\ndef view():\r\n conn = sqlite3.connect(\"fooddata.db\")\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM food1\")\r\n rows = cur.fetchall()\r\n conn.close()\r\n return rows\r\n\r\ndef search(itemid=\"\", price=\"\"):\r\n conn = sqlite3.connect(\"fooddata.db\")\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM food1 WHERE itemid=? OR price=?\", (itemid, price))\r\n rows = cur.fetchall()\r\n conn.close()\r\n return rows\r\nconnect()\r\n\r\n","sub_path":"backendadmin.py","file_name":"backendadmin.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"410618373","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\ndef calc_warp(image_size, vanishing_point, percent_visible, width_compression):\n top_left, top_right, bottom_right, bottom_left = np.float32([\n (0, 0),\n (image_size[0], 0),\n (image_size[0], image_size[1]),\n (0, image_size[1])\n ])\n src = np.float32([\n bottom_left + (vanishing_point - bottom_left) * percent_visible,\n bottom_right + (vanishing_point - bottom_right) * percent_visible,\n bottom_right,\n bottom_left\n ])\n width = top_right[0] - top_left[0]\n compressed_width = width * width_compression\n offset = ((width - compressed_width) / 2, 0)\n dst = np.float32([\n top_left + offset,\n top_right - offset,\n bottom_right - offset,\n bottom_left + offset\n ])\n M = cv2.getPerspectiveTransform(src, dst)\n Minv = cv2.getPerspectiveTransform(dst, src)\n return lambda img: cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR),\\\n lambda img: cv2.warpPerspective(img, Minv, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)\n\n\n\n\ndef main():\n vanishing_point = (639,419)\n forward, backward = calc_warp((1280,720), vanishing_point, .9, .75)\n img = mpimg.imread('test_images/straight_lines2.jpg')\n cv2.line(img, (0,720), vanishing_point, (255,0,0), 4)\n cv2.line(img, (1280,720), vanishing_point, (255,0,0), 4)\n warped = forward(img)\n plt.subplot(121); plt.imshow(img)\n plt.subplot(122); plt.imshow(warped)\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"perspective.py","file_name":"perspective.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"517617484","text":"\nimport matplotlib as mpl\nmpl.use('Agg')\n\nimport pylab as pl\nimport numpy as np\n\n\ndef lognorm_pdf(x, mu, sig):\n S = - (np.log(x) - mu)**2/(2.*sig**2)\n f_x = 1./(x*sig*np.sqrt(2.*np.pi)) * np.exp(S)\n return f_x\n\nfrom scipy.stats import norm, lognorm\n\nmu = 2.\nsigma = 1.\n\nxs = lognorm.rvs(s=sigma, scale=np.exp(mu), size=500000)\n\nfig, ((ax1, ax2),(ax3,ax4)) = pl.subplots(2,2)\naxs = [ax1,ax2,ax3,ax4]\n\nfig.set_size_inches(8,6.)\n\nbin_min, bin_max = 0,80\nbin_N = 1000\ns=0.01\n\nxr = np.arange(bin_min, bin_max+s, s)\n\n\n# ------- ax1: linear x-scale ---------\nax1.set_xlim(0,bin_max)\nax1.hist(xs, np.linspace(bin_min, bin_max, bin_N), normed=True)\nax1.plot(xr, lognorm_pdf(xr, mu, sigma), 'r')\n\nfs, floc, fscale = lognorm.fit(xs, floc=0)\nf_rv = lognorm(fs, loc=0, scale=fscale)\n\nax1.plot(xr, f_rv.pdf(xr), lw=2, color='grey',\n linestyle='--', dashes=(1, 1.6))\n\n\n\n# ------- ax2: log vals on linear x-scale no normalization ---------\nax2.plot(np.log10(xr), lognorm_pdf(xr, mu, sigma), 'r')\n_, bins, _ = ax2.hist(np.log10(xs), bins=bin_N, normed=True)\n\n\nfloc, fscale = norm.fit(np.log10(xs))\nf_rv = norm(loc=floc, scale=fscale)\n\nxsp = np.arange(-2, 3, 0.01)\nxr = np.arange(10.**(bins[0]), 10.**(bins[-1])*1.1, s)\nax2.plot(xsp, f_rv.pdf(xsp), lw=2, color='grey',\n linestyle='--', dashes=(1, 1.6))\n\nfs, floc, fscale = lognorm.fit(xs, floc=0)\nf_rv = lognorm(fs, loc=0, scale=fscale)\n\n# ax2.plot(np.log10(xr), f_rv.pdf(xr), lw=2, color='green',\n# linestyle='--', dashes=(1, 1.6))\nax2.plot(xsp, f_rv.pdf(10**xsp), lw=2, color='green',\n linestyle='--', dashes=(1, 1.6))\n\n\n\n# ---------\ncounts, edges = np.histogram(xs, bins=np.linspace(bin_min, bin_max, bin_N),\n density=True)\ncenters = (edges[1:] + edges[:-1])/2.\nax3.plot(np.log10(centers), counts, '.', color='k')\nax3.plot(np.log10(xr), lognorm_pdf(xr, mu, sigma), 'r')\n\n\n\nax1.set_xlabel('x')\nax2.set_xlabel('log(x)')\nax3.set_xlabel('x')\nax4.set_xlabel('x')\n\nfor ax in axs:\n ax.set_ylabel('f(x)')\n\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.yaxis.set_ticks_position('left')\n ax.xaxis.set_ticks_position('bottom')\n\nax4.hist(xs, 10**np.linspace(-2,2,bin_N), normed=True)\nax4.set_xscale('log')\nax4.plot(xr, lognorm_pdf(xr, mu, sigma), 'r')\n\n\nimport os\nfname = os.path.splitext(os.path.basename(__file__))[0]\n\npl.tight_layout()\npl.savefig(\"{}.png\".format(fname), dpi=300, bbox_inches='tight')\n\n\n\n","sub_path":"fig1.py","file_name":"fig1.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"468013165","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 2 15:39:05 2020\r\n\r\n@author: rfuchs\r\n\"\"\"\r\n\r\nfrom data_preprocessing import bin_to_bern\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.linear_model import LogisticRegression\r\n# Dirty local hard copy of the Github bevel package\r\nfrom bevel.linear_ordinal_regression import OrderedLogit \r\n\r\nimport autograd.numpy as np\r\n\r\ndef rl1_selection(y_bin, y_ord, y_categ, zl1_ys, w_s):\r\n ''' Selects the number of factors on the first latent discrete layer \r\n y_bin (n x p_bin ndarray): The binary and count data matrix\r\n y_ord (n x p_ord ndarray): The ordinal data matrix\r\n y_categ (n x p_categ ndarray): The categorical data matrix\r\n zl1_ys (k_1D x r_1D ndarray): The first layer latent variables\r\n w_s (list): The path probabilities starting from the first layer\r\n ------------------------------------------------------------------\r\n return (list of int): The dimensions to keep for the GLLVM layer\r\n '''\r\n \r\n M0 = zl1_ys.shape[0]\r\n numobs = zl1_ys.shape[1] \r\n r0 = zl1_ys.shape[2]\r\n S0 = zl1_ys.shape[3] \r\n\r\n nb_bin = y_bin.shape[1]\r\n nb_ord = y_ord.shape[1]\r\n nb_categ = y_categ.shape[1]\r\n \r\n PROP_ZERO_THRESHOLD = 0.25\r\n PVALUE_THRESHOLD = 0.10\r\n \r\n # Detemine the dimensions that are weakest for Binomial variables\r\n zero_coef_mask = np.zeros(r0)\r\n for j in range(nb_bin):\r\n for s in range(S0):\r\n Nj = np.max(y_bin[:,j]) # The support of the jth binomial is [1, Nj]\r\n if Nj == 1: # If the variable is Bernoulli not binomial\r\n yj = y_bin[:,j]\r\n z = zl1_ys[:,:,:,s]\r\n else: # If not, need to convert Binomial output to Bernoulli output\r\n yj, z = bin_to_bern(Nj, y_bin[:,j], z[0])\r\n \r\n # Put all the M0 points in a series\r\n X = z.flatten(order = 'C').reshape((M0 * numobs, r0), order = 'C')\r\n y_repeat = np.repeat(yj, M0).astype(int) # Repeat rather than tile to check\r\n \r\n lr = LogisticRegression(penalty = 'l1', solver = 'saga')\r\n lr.fit(X, y_repeat)\r\n zero_coef_mask += (lr.coef_[0] == 0) * w_s[s]\r\n \r\n # Detemine the dimensions that are weakest for Ordinal variables\r\n for j in range(nb_ord):\r\n for s in range(S0):\r\n ol = OrderedLogit()\r\n X = zl1_ys[:,:,:,s].flatten(order = 'C').reshape((M0 * numobs, r0), order = 'C')\r\n y_repeat = np.repeat(y_ord[:, j], M0).astype(int) # Repeat rather than tile to check\r\n \r\n ol.fit(X, y_repeat)\r\n zero_coef_mask += np.array(ol.summary['p'] > PVALUE_THRESHOLD) * w_s[s]\r\n \r\n # Detemine the dimensions that are weakest for Categorical variables\r\n for j in range(nb_categ):\r\n for s in range(S0):\r\n z = zl1_ys[:,:,:,s]\r\n \r\n # Put all the M0 points in a series\r\n X = z.flatten(order = 'C').reshape((M0 * numobs, r0), order = 'C')\r\n y_repeat = np.repeat(y_categ[:,j], M0).astype(int) # Repeat rather than tile to check\r\n \r\n lr = LogisticRegression(penalty = 'l1', solver = 'saga', \\\r\n multi_class = 'multinomial') \r\n lr.fit(X, y_repeat) \r\n \r\n zero_coef_mask += (lr.coef_[0] == 0) * w_s[s] \r\n \r\n # Voting: Delete the dimensions which have been zeroed a majority of times \r\n zeroed_coeff_prop = zero_coef_mask / ((nb_ord + nb_bin + nb_categ))\r\n \r\n # Need at least r1 = 2 for algorithm to work\r\n new_rl = np.sum(zeroed_coeff_prop <= PROP_ZERO_THRESHOLD)\r\n \r\n if new_rl < 2:\r\n dims_to_keep = np.argsort(zeroed_coeff_prop)[:2]\r\n \r\n else:\r\n dims_to_keep = list(set(range(r0)) - \\\r\n set(np.where(zeroed_coeff_prop > PROP_ZERO_THRESHOLD)[0].tolist()))\r\n\r\n dims_to_keep = np.sort(dims_to_keep)\r\n \r\n return dims_to_keep\r\n\r\n\r\ndef other_r_selection(rl1_select, z2_z1s):\r\n ''' Chose the meaningful dimensions from the second layer to the end of the network\r\n rl1_select (list): The dimension kept over the first layer \r\n z2_z1s (list of ndarrays): z^{(l + 1)}| z^{(l)}, s\r\n --------------------------------------------------------------------------\r\n return (list of int): The dimensions to keep from the second layer of the network\r\n '''\r\n \r\n S = [zz.shape[2] for zz in z2_z1s] + [1] \r\n CORR_THRESHOLD = 0.20\r\n \r\n L = len(z2_z1s)\r\n M = np.array([zz.shape[0] for zz in z2_z1s] + [z2_z1s[-1].shape[1]])\r\n prev_new_r = [len(rl1_select)]\r\n \r\n dims_to_keep = []\r\n \r\n for l in range(L): \r\n # Will not keep the following layers if one of the previous layer is of dim 1\r\n if prev_new_r[l] <= 1:\r\n dims_to_keep.append([])\r\n prev_new_r.append(0)\r\n \r\n else: \r\n old_rl = z2_z1s[l].shape[-1]\r\n corr = np.zeros(old_rl)\r\n \r\n for s in range(S[l]):\r\n for m1 in range(M[l + 1]):\r\n pca = PCA(n_components=1)\r\n pca.fit_transform(z2_z1s[l][m1, :, s])\r\n corr += np.abs(pca.components_[0])\r\n \r\n average_corr = corr / (S[l] * M[l + 1])\r\n new_rl = np.sum(average_corr > CORR_THRESHOLD)\r\n \r\n if prev_new_r[l] > new_rl: # Respect r1 > r2 > r3 ....\r\n wanted_dims = np.where(average_corr > CORR_THRESHOLD)[0].tolist()\r\n wanted_dims = np.sort(wanted_dims) \r\n dims_to_keep.append(wanted_dims)\r\n \r\n else: # Have to delete other dimensions to match r1 > r2 > r3 ....\r\n nb_dims_to_remove = old_rl - prev_new_r[l] + 1\r\n unwanted_dims = np.argpartition(average_corr, nb_dims_to_remove)[:nb_dims_to_remove]\r\n wanted_dims = list(set(range(old_rl)) - set(unwanted_dims))\r\n wanted_dims = np.sort(wanted_dims)\r\n dims_to_keep.append(wanted_dims)\r\n new_rl = len(wanted_dims)\r\n \r\n prev_new_r.append(new_rl)\r\n\r\n return dims_to_keep\r\n\r\n\r\ndef r_select(y_bin, y_ord, y_categ, zl1_ys, z2_z1s, w_s):\r\n ''' Automatic choice of dimension of all layer components \r\n y_bin (numobs x nb_bin nd-array): The binary/count data\r\n y_ord (numobs x nb_ord nd-array): The ordinal data\r\n y_categ (numobs x nb_categ nd-array): The categorical data\r\n \r\n yc (numobs x nb_categ nd-array): The continuous data\r\n \r\n zl1_ys (ndarray): The latent variable of the first layer\r\n z2_z1s (list of ndarray): z^{l+1} | z^{l}, s, Theta for all (l,s) \r\n w_s (list): The path probabilities for all s in [1,S]\r\n --------------------------------------------------------------------------\r\n returns (dict): The dimensions kept for all the layers of the network\r\n '''\r\n \r\n rl1_select = rl1_selection(y_bin, y_ord, y_categ, zl1_ys, w_s)\r\n other_r_select = other_r_selection(rl1_select, z2_z1s)\r\n return [rl1_select] + other_r_select\r\n\r\ndef k_select(w_s, k, new_L, clustering_layer):\r\n ''' Automatic choice of the number of components by layer \r\n w_s (list): The path probabilities for all s in [1,S]\r\n k (dict): The number of component on each layer\r\n new_L (int): The selected total number of layers.\r\n clustering_layer (int): The index of the clustering layer\r\n --------------------------------------------------------------------------\r\n returns (dict): The components kept for all the layers of the network\r\n '''\r\n \r\n L = len(k)\r\n n_clusters = k[clustering_layer]\r\n \r\n # If the clustering layer (cl) is deleted, define the last existing layer as cl \r\n last_layer_idx = new_L - 1\r\n if last_layer_idx < clustering_layer:\r\n clustering_layer = last_layer_idx\r\n \r\n components_to_keep = []\r\n w = w_s.reshape(*k, order = 'C')\r\n \r\n for l in range(new_L):\r\n \r\n PROBA_THRESHOLD = 1 / (k[l] * 4)\r\n\r\n other_layers_indices = tuple(set(range(L)) - set([l]))\r\n components_proba = w.sum(other_layers_indices)\r\n #print(components_proba)\r\n \r\n if l == clustering_layer:\r\n biggest_lik_comp = np.sort(components_proba.argsort()[::-1][:n_clusters])\r\n components_to_keep.append(biggest_lik_comp)\r\n\r\n else:\r\n comp_kept = np.where(components_proba > PROBA_THRESHOLD)[0]\r\n comp_kept = np.sort(comp_kept)\r\n components_to_keep.append(comp_kept)\r\n \r\n return components_to_keep","sub_path":"DDGMM/parameter_selection.py","file_name":"parameter_selection.py","file_ext":"py","file_size_in_byte":8688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"292442898","text":"import numpy as np\n\n\ndef zero_crossing_rate(eeg_epoch):\n eeg_epoch = np.asarray(eeg_epoch)\n zero_crosses = np.nonzero(np.diff(eeg_epoch > 0))[0]\n return zero_crosses.size\n\n\ndef calc_hjorth_params(eeg_epoch):\n eeg_epoch = np.asarray(eeg_epoch)\n first_deriv = np.diff(eeg_epoch)\n second_deriv = np.diff(eeg_epoch, 2)\n\n var_zero = np.mean(eeg_epoch ** 2)\n var_d1 = np.mean(first_deriv ** 2)\n var_d2 = np.mean(second_deriv ** 2)\n\n activity = var_zero\n morbidity = np.sqrt(var_d1 / var_zero)\n complexity = np.sqrt(var_d2 / var_d1) / morbidity\n\n return activity, morbidity, complexity\n","sub_path":"timedanalysis.py","file_name":"timedanalysis.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"513959436","text":"import cv2\nimport sys\nfrom core.edges.detect import EdgeDetectorFactory\n\n\nimg_path = str(sys.argv[1])\nthreshold = int(sys.argv[2])\nkernel_size = int(sys.argv[3])\ninside = int(sys.argv[4]) == 1\n\nedge_detector = EdgeDetectorFactory().createClosingMorphEdgeDetector(threshold, kernel_size, inside)\nimg = cv2.cvtColor(cv2.imread(img_path, 1), cv2.COLOR_BGR2GRAY)\ncontour = edge_detector.getEdges(img)\ncv2.imshow('contour', contour)\ncv2.waitKey(0)\ncv2.imwrite('contour.png', contour)\n\nexit(0)","sub_path":"get_contour.py","file_name":"get_contour.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"346175958","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport os\n\nfrom src.build import build_common\nfrom src.build import ninja_generator\nfrom src.build import toolchain\nfrom src.build.build_options import OPTIONS\n\n\nclass GmsCoreNinjaGenerator(ninja_generator.ApkNinjaGenerator):\n if OPTIONS.internal_apks_source_is_internal():\n _DIST_DIR = 'out/gms-core-build/dist'\n _ORIGINAL_APK_PATH = 'out/gms-core-build/play_services.apk'\n _NOTICES_OUTPUT_PATH = 'out/gms-core-build/NOTICES.tar.gz'\n else:\n # Use archived build\n _DIST_DIR = 'out/internal-apks'\n _ORIGINAL_APK_PATH = 'out/internal-apks/play_services.apk'\n _NOTICES_OUTPUT_PATH = 'out/internal-apks/play_services_NOTICES.tar.gz'\n\n if OPTIONS.enable_art_aot():\n _APK_PATH = build_common.get_build_path_for_apk('play_services',\n 'optimized.apk',\n is_target=True)\n else:\n _APK_PATH = _ORIGINAL_APK_PATH\n\n APITEST_APK_PATH = os.path.join(_DIST_DIR, 'GmsCoreApiTests.apk')\n APITEST_SETUP_APK_PATH = os.path.join(_DIST_DIR, 'GmsCoreApiTestsSetup.apk')\n _PROGUARD_MAPPING = os.path.join(_DIST_DIR, 'GmsCore-proguard-mapping.txt')\n\n # Every build artifact of GMS Core for ninja to generate dependencies.\n _ALL_OUTPUTS = [_ORIGINAL_APK_PATH, _NOTICES_OUTPUT_PATH, APITEST_APK_PATH,\n APITEST_SETUP_APK_PATH]\n if not OPTIONS.is_debug_code_enabled():\n _ALL_OUTPUTS.append(_PROGUARD_MAPPING)\n\n def __init__(self, extra_dex2oat_flags):\n super(GmsCoreNinjaGenerator, self).__init__(\n 'play_services',\n install_path='/vendor/play_services',\n canned_classes_apk=GmsCoreNinjaGenerator._APK_PATH,\n extra_dex2oat_flags=extra_dex2oat_flags)\n\n def build_gms_core_or_use_prebuilt(self):\n if OPTIONS.enable_art_aot():\n # Rule for pre-optimizing gms-core apk.\n boot_image_dir = os.path.join(build_common.get_android_fs_root(),\n 'system/framework',\n build_common.get_art_isa())\n self.rule(\n 'gms_core_apk_preoptimize',\n 'src/build/gms_core_apk_preoptimize.py --input $in --output $out',\n description='Preoptimizing gmscore sub apks contained in $in')\n self.build(GmsCoreNinjaGenerator._APK_PATH,\n 'gms_core_apk_preoptimize',\n GmsCoreNinjaGenerator._ORIGINAL_APK_PATH,\n implicit=[toolchain.get_tool('java', 'dex2oat'),\n os.path.join(boot_image_dir, 'boot.art'),\n os.path.join(boot_image_dir, 'boot.oat')])\n\n if not OPTIONS.internal_apks_source_is_internal():\n return\n\n flags = '--eng' if OPTIONS.is_debug_code_enabled() else ''\n build_log = os.path.join('out/gms-core-build/build.log')\n command = ('internal/build/build.py gms-core %s > %s 2>&1 || '\n '(cat %s; exit 1)') % (flags, build_log, build_log)\n\n if OPTIONS.internal_apks_source() == 'internal-dev':\n # Only for local development. play-services.apk dependes on jars below to\n # build, just to use ARC specific feature like ArcMessageBridge and\n # Tracing. This dependency is a must-have for a clean build. But this\n # dependency can cause unrelated framework change to trigger rebuild of\n # play-services.apk, which is very slow. With this option, eng will self\n # manages the dependency, which is almost always satisfied.\n jars = []\n else:\n # Simply make these jars the dependencies of gms-core-build, which\n # references ArcMessage and ArcMessageBridge in the jar. Note that these\n # jars changes often and is like to cause unnecessary rebuild of gms-core,\n # which is very slow. We may think about a way to minimize the\n # dependency.\n #\n # See also: internal/mods/gms-core/vendor/unbundled_google/packages/ \\\n # OneUp/package/Android.mk\n # OneUp/package/generate_package.mk\n jars = [\n build_common.get_build_path_for_jar('arc-services-framework',\n subpath='classes.jar'),\n build_common.get_build_path_for_jar('framework',\n subpath='classes.jar'),\n ]\n\n self.build(GmsCoreNinjaGenerator._ALL_OUTPUTS,\n 'run_shell_command',\n implicit=['src/build/DEPS.arc-int'] + jars,\n variables={'command': command})\n\n def package_and_install(self):\n self.set_notice_archive(GmsCoreNinjaGenerator._NOTICES_OUTPUT_PATH)\n self.package()\n self.install()\n\n\nclass GmsCoreApiTestNinjaGenerator(ninja_generator.ApkNinjaGenerator):\n def __init__(self, **kwargs):\n super(GmsCoreApiTestNinjaGenerator, self).__init__(\n 'GmsCoreApiTests', **kwargs)\n\n def build_test_list(self):\n return self._build_test_list_for_apk(GmsCoreNinjaGenerator.APITEST_APK_PATH)\n","sub_path":"src/build/gms_core_ninja_generator.py","file_name":"gms_core_ninja_generator.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"184434564","text":"# class Dispatcher:\n# def __init__(self):\n# self._run()\n#\n# def cmd1(self):\n# print(\"I'm cmd1\")\n#\n# def cmd2(self):\n# print(\"I'm cmd2\")\n#\n# def _run(self):\n# while True:\n# cmd = input('Plz input a command: ').strip()\n# if cmd == 'quit' or cmd == 'q':\n# break\n# getattr(self, cmd, lambda: print('Unknown Command {}.'.format(cmd)))()\n\n\n# 执行Dispatcher类实例化时就可以执行_run方法,之后通过getattr函数来判断用户输入的命令是否在类中有定义,\n# getattr()可以通过name返回object的属性值。当属性不存在,将使用default返回,如果没有default,则抛出\n# AttributeError。name必须为字符串。这里判断实例中是否有cmd,这个cmd就是while True中定义的用户输入的命\n# 令,如果找到,就返回用户输入的方法名的结果。否则返回Unknown Command {cmd}.最后的括号表示找到用户输入的\n# 方法名后,要调用这个方法,打印这个方法的执行结果,如cmd1方法的执行结果\n# Dispatcher()\n# ===========================================================================================\n# def dispatcher():\n# cmds = {}\n# def reg(cmd, fn):\n# if isinstance(cmd, str):\n# cmds[cmd] = fn\n# else:\n# print('error')\n#\n# def run():\n# while True:\n# cmd = input(\"plz input command: \")\n# if cmd.strip() == 'quit':\n# return\n# cmds.get(cmd.strip(), defaultfn)()\n# print(cmds)\n#\n# def defaultfn():\n# pass\n#\n# return reg,run\n#\n# reg,run = dispatcher()\n# reg('cmd1', lambda :1)\n# reg('cmd2', lambda :2)\n#\n# run()\n# =============================\n# 把上面的分发器函数改成类\nclass dispatcher():\n def cmd1(self):\n print('cmd1')\n\n def reg(self, cmd, fn):\n if isinstance(cmd, str):\n setattr(type(self), cmd, fn)\n else:\n print('error')\n\n def run(self):\n while True:\n cmd = input(\"plz input command : \")\n if cmd.strip() == 'quit':\n return\n getattr(self, cmd.strip(), self.defaultfn)()\n\n def defaultfn(self):\n print('default')\n\ndis = dispatcher()\n\ndis.reg('cmd2', lambda self:print(2))\ndis.reg('cmd3', lambda self:print(3))\n\ndis.run()","sub_path":"练习/面向对象/魔术方法/重要练习:命令分发器,通过名称找对应的函数执行。.py","file_name":"重要练习:命令分发器,通过名称找对应的函数执行。.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290128876","text":"import os\n\nfrom jt.invest.constants import w_db, futils\nfrom jt.utils.misc.log import Logger\n\nfrom seo.constants import root\n\nlog = Logger()\n\ndef check_project(start_dt='20200401'):\n # 检查已完成项目是否已经归档\n all_project = futils.get_current_folder_dirs(os.path.join(root, '00 项目资料'))\n\n sql = f\"\"\"\n select b.S_INFO_NAME+'_'+left(a.S_INFO_WINDCODE,6) as symbol\n from ASHARESEO a, ASHAREDESCRIPTION b\n where a.S_FELLOW_PROGRESS='3'\n and a.S_FELLOW_DATE>='{start_dt}'\n and a.IS_NO_PUBLIC=1 \n and a.PRICINGMODE='275001000'\n and a.S_FELLOW_ISSUETYPE = '439006000'\n and a.S_INFO_WINDCODE = b.S_INFO_WINDCODE\n order by a.S_FELLOW_DATE desc;\n \"\"\"\n df = w_db.read(sql)\n\n for _p in all_project: \n if _p in df.symbol.values:\n f = os.path.join(root, '00 项目资料')\n t = os.path.join(root, '00 项目资料', '00 归档')\n log.info(f'Archive dir {_p}')\n futils.move_dir(_p, f, t, copy_=False, replace_=True)\n \n all_material = futils.get_current_folder_files(os.path.join(root, '01 路演材料'))\n\n for _m in all_material:\n for _n in df.symbol.values:\n if _n[:-7] in _m:\n f = os.path.join(root, '01 路演材料')\n t = os.path.join(root, '01 路演材料', '已实施项目')\n log.info(f'Archive mateiral {_m}')\n futils.move_file(_m, f, t, copy_=False)\n\n # 检查未跟踪项目\n sql = f\"\"\"\n select b.S_INFO_NAME+'_'+left(a.S_INFO_WINDCODE,6) as symbol, LEADUNDERWRITER as writer\n from ASHARESEO a, ASHAREDESCRIPTION b\n where a.S_FELLOW_PROGRESS='5'\n and a.S_FELLOW_APPROVEDDATE>='{start_dt}'\n and a.IS_NO_PUBLIC=1 \n and a.PRICINGMODE='275001000'\n and a.S_FELLOW_ISSUETYPE = '439006000'\n and a.S_INFO_WINDCODE = b.S_INFO_WINDCODE\n order by a.S_FELLOW_APPROVEDDATE desc;\n \"\"\"\n\n df = w_db.read(sql)\n all_project = futils.get_current_folder_dirs(os.path.join(root, '00 项目资料'))\n\n p_name, p_writer = list(), list()\n for i in df.index:\n if not df.loc[i, 'symbol'] in all_project:\n p_name.append(df.loc[i, 'symbol'][:-7])\n p_writer.append(df.loc[i, 'writer'])\n log.info(f\"Not tracked project {df.loc[i, 'symbol']}, main writer {df.loc[i, 'writer']}\")\n log.info(p_name)\n log.info(p_writer)\n return p_name, p_writer\n\n \nif __name__ == \"__main__\":\n check_project('20210223')\n\n \n","sub_path":"src/seo/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"291911515","text":"#!/usr/bin/env python\n\nfrom gppylib.gpparseopts import OptParser, OptChecker\nfrom gppylib.operations.backup_utils import split_fqn, checkAndRemoveEnclosingDoubleQuote, removeEscapingDoubleQuoteInSQLString, \\\n escapeDoubleQuoteInSQLString\nimport re\nimport sys\nimport os\n\nsearch_path_expr = 'SET search_path = '\nset_start = 'S'\nlen_search_path_expr = len(search_path_expr)\nset_expr = 'SET '\n\nextra_rule_keyword = [' WHERE ', ' DO ']\ncomment_start_expr = '--'\ncomment_expr = '-- Name: '\ncomment_data_expr = '-- Data: '\ntype_expr = '; Type: '\nschema_expr = '; Schema: '\n\ncommand_start_expr = 'CREATE '\n\ndef get_type(line):\n temp = line.strip()\n type_start = find_all_expr_start(temp, type_expr)\n schema_start = find_all_expr_start(temp, schema_expr)\n if len(type_start) != 1 or len(schema_start) != 1:\n return None\n type = temp[type_start[0] + len(type_expr) : schema_start[0]]\n return type\n\ndef find_all_expr_start(line, expr):\n \"\"\"\n Find all overlapping matches\n \"\"\"\n return [m.start() for m in re.finditer('(?=%s)' % expr, line)]\n\ndef locate_unquoted_keyword(line, keyword):\n indexes = find_all_expr_start(line, keyword)\n if len(indexes) > 0:\n for idx in indexes:\n if len(find_all_expr_start(line[ : idx], '\"')) % 2 == 0 and len(find_all_expr_start(line[idx + len(keyword) : ], '\"')) % 2 == 0:\n return idx\n else:\n return -1\n\ndef process_schema(dump_schemas, dump_tables, fdin, fdout, change_schema_name=None, schema_level_restore_list=None):\n \"\"\"\n Filter the dump file line by line from restore\n dump_schemas: set of schemas to restore\n dump_tables: set of (schema, table) tuple to restore\n fdin: stdin from dump file\n fdout: to write filtered content to stdout\n change_schema_name: different schema name to restore\n schema_level_restore_list: list of schemas to restore all tables under them\n \"\"\"\n schema = None\n schema_wo_escaping = None\n type = None\n schema_buff = ''\n output = False\n further_investigation_required = False\n search_path = False\n line_buf = None\n for line in fdin:\n if (line[0] == set_start) and line.startswith(search_path_expr):\n output = False\n further_investigation_required = False\n # schema in set search_path line is already escaped in dump file\n schema = extract_schema(line)\n schema_wo_escaping = removeEscapingDoubleQuoteInSQLString(schema, False)\n if ((dump_schemas and schema_wo_escaping in dump_schemas) or \n (schema_level_restore_list and schema_wo_escaping in schema_level_restore_list)):\n if change_schema_name and len(change_schema_name) > 0:\n # change schema name can contain special chars including white space, double quote that.\n # if original schema name is already quoted, replaced it with quoted change schema name\n quoted_schema = '\"' + schema + '\"'\n if quoted_schema in line:\n line = line.replace(quoted_schema, escapeDoubleQuoteInSQLString(change_schema_name))\n else:\n line = line.replace(schema, escapeDoubleQuoteInSQLString(change_schema_name))\n search_path = True\n schema_buff = line\n elif (line[0] == set_start) and line.startswith(set_expr):\n output = True\n elif line[:2] == comment_start_expr:\n if line.startswith(comment_expr):\n type = get_type(line)\n output = False\n elif type and (line[:7] == 'CREATE ' or line[:8] == 'REPLACE '):\n if type == 'RULE':\n output = check_table(schema_wo_escaping, line, ' TO ', dump_tables, schema_level_restore_list, is_rule=True)\n elif type == 'INDEX':\n output = check_table(schema_wo_escaping, line, ' ON ', dump_tables, schema_level_restore_list)\n elif type == 'TRIGGER':\n line_buf = line\n further_investigation_required = True\n elif type and type in ['CONSTRAINT', 'FK CONSTRAINT'] and line[:12] == 'ALTER TABLE ':\n if line.startswith('ALTER TABLE ONLY'):\n output = check_table(schema_wo_escaping, line, ' ONLY ', dump_tables, schema_level_restore_list)\n else:\n output = check_table(schema_wo_escaping, line, ' TABLE ', dump_tables, schema_level_restore_list)\n elif further_investigation_required:\n if type == 'TRIGGER':\n output = check_table(schema_wo_escaping, line, ' ON ', dump_tables, schema_level_restore_list)\n if not output:\n line_buf = None\n further_investigation_required = False\n\n if output:\n if search_path:\n fdout.write(schema_buff)\n schema_buff = None\n search_path = False\n if line_buf:\n fdout.write(line_buf)\n line_buf = None\n fdout.write(line)\n\n# Given a line like 'ALTER TABLE ONLY tablename\\n' and a search_str like ' ONLY ',\n# extract everything between the search_str and the next space or the end of the string, whichever comes first.\ndef check_table(schema, line, search_str, dump_tables, schema_level_restore_list=None, is_rule=False):\n if schema_level_restore_list and schema in schema_level_restore_list:\n return True\n\n if dump_tables:\n try:\n comp_set = set()\n start = line.index(search_str) + len(search_str)\n if is_rule:\n # cut the line nicely based on extra keyword for create rule statement\n # in case [WHERE condition] clause contains any special chars, cut before WHERE\n end = locate_unquoted_keyword(line, extra_rule_keyword[0])\n if end == -1:\n end = locate_unquoted_keyword(line, extra_rule_keyword[1])\n line = line[:end]\n\n dot_separator_idx = line.find('.')\n last_double_quote_idx = line.rfind('\"')\n\n has_schema_table_fmt = True if dot_separator_idx != -1 else False\n has_special_chars = True if last_double_quote_idx != -1 else False\n\n if not has_schema_table_fmt and not has_special_chars:\n table = line[start:].split()[0]\n elif has_schema_table_fmt and not has_special_chars:\n full_table_name = line[start:].split()[0]\n _, table = split_fqn(full_table_name)\n elif not has_schema_table_fmt and has_special_chars:\n table = line[start : last_double_quote_idx + 1]\n else:\n if dot_separator_idx < last_double_quote_idx:\n # table name is double quoted\n full_table_name = line[start : last_double_idx + 1]\n else:\n # only schema name double quoted\n ending_space_idx = line.find(' ', dot_separator_idx)\n full_table_name = line[start : ending_space_idx]\n _, table = split_fqn(full_table_name)\n\n table = checkAndRemoveEnclosingDoubleQuote(table)\n table = removeEscapingDoubleQuoteInSQLString(table, False)\n comp_set.add((schema, table))\n\n if comp_set.issubset(dump_tables):\n return True\n return False\n except:\n return False\n else:\n return False\n\ndef get_table_schema_set(filename):\n \"\"\"\n filename: file with true schema and table name (none escaped), don't strip white space\n on schema and table name in case it's part of the name\n \"\"\"\n dump_schemas = set()\n dump_tables = set()\n\n with open(filename) as fd:\n contents = fd.read()\n tables = contents.splitlines()\n for t in tables:\n schema, table = split_fqn(t)\n dump_tables.add((schema, table))\n dump_schemas.add(schema)\n return (dump_schemas, dump_tables)\n\ndef extract_schema(line):\n \"\"\"\n Instead of searching ',' in forwarding way, search ', pg_catalog;' \n reversely, in case schema name contains comma.\n\n Remove enclosing double quotes only, in case quote is part of the\n schema name\n \"\"\"\n temp = line[len_search_path_expr:]\n idx = temp.rfind(\", pg_catalog;\")\n if idx == -1:\n return None\n schema = temp[:idx]\n return checkAndRemoveEnclosingDoubleQuote(schema)\n\ndef get_change_schema_name(change_schema_file):\n \"\"\"\n Only strip the '\\n' as it is one of the non-supported chars to be part\n of the schema or table name \n \"\"\"\n if not os.path.exists(change_schema_file):\n raise Exception('change schema file path %s does not exist' % change_schema_file)\n change_schema_name = None\n with open(change_schema_file) as fr:\n line = fr.read()\n change_schema_name = line.strip('\\n')\n return change_schema_name\n\ndef get_schema_level_restore_list(schema_level_restore_file=None):\n \"\"\"\n Note: white space in schema and table name is supported now, don't do strip on them\n \"\"\"\n if not os.path.exists(schema_level_restore_file):\n raise Exception('schema level restore file path %s does not exist' % schema_level_restore_file)\n schema_level_restore_list = []\n with open(schema_level_restore_file) as fr:\n schema_entries = fr.read()\n schema_level_restore_list = schema_entries.splitlines()\n return schema_level_restore_list\n\n\nif __name__ == \"__main__\":\n parser = OptParser(option_class=OptChecker)\n parser.remove_option('-h')\n parser.add_option('-h', '-?', '--help', action='store_true')\n parser.add_option('-t', '--tablefile', type='string', default=None)\n parser.add_option('-c', '--change-schema-file', type='string', default=None)\n parser.add_option('-s', '--schema-level-file', type='string', default=None)\n (options, args) = parser.parse_args()\n if not (options.tablefile or options.schema_level_file):\n raise Exception('-t table file name or -s schema level file name must be specified')\n elif options.schema_level_file and options.change_schema_file:\n raise Exception('-s schema level file option can not be specified with -c change schema file option')\n\n schemas, tables = None, None\n if options.tablefile:\n (schemas, tables) = get_table_schema_set(options.tablefile)\n\n change_schema_name = None\n if options.change_schema_file:\n change_schema_name = get_change_schema_name(options.change_schema_file)\n\n schema_level_restore_list = None\n if options.schema_level_file:\n schema_level_restore_list = get_schema_level_restore_list(options.schema_level_file)\n\n process_schema(schemas, tables, sys.stdin, sys.stdout, change_schema_name, schema_level_restore_list)\n","sub_path":"gpMgmt/bin/gprestore_post_data_filter.py","file_name":"gprestore_post_data_filter.py","file_ext":"py","file_size_in_byte":10912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"538949801","text":"import json\nimport base64\nimport io\nfrom PIL import Image\nimport yaml\nimport numpy as np\nfrom PIL import Image\nfrom vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor\n\n\ndef init_context(context):\n context.logger.info(\"Init context... 0%\")\n\n net_type = 'mb1-ssd'\n class_names = ['background', 'person']\n net = create_mobilenetv1_ssd(len(class_names), is_test=True)\n net.load('/opt/nuclio/common/model.pth')\n predictor = create_mobilenetv1_ssd_predictor(net, candidate_size=200)\n\n setattr(context.user_data, 'model_handler', predictor)\n functionconfig = yaml.safe_load(open(\"/opt/nuclio/function.yaml\"))\n context.logger.info(\"Init context...100%\")\n\ndef handler(context, event):\n context.logger.info(\"Run mb-ssd person detector\")\n data = event.body\n buf = io.BytesIO(base64.b64decode(data[\"image\"].encode('utf-8')))\n threshold = float(data.get(\"threshold\", 0.5))\n image = np.array(Image.open(buf))[..., :3]\n\n boxes, labels, probs = context.user_data.model_handler.predict(image, 20, threshold)\n\n results = []\n for box, score in zip(boxes, probs):\n label = \"person\"\n if score >= threshold:\n results.append({\n \"confidence\": str(float(score)),\n \"label\": label,\n \"points\": box.tolist(),\n \"type\": \"rectangle\",\n })\n\n return context.Response(body=json.dumps(results), headers={},\n content_type='application/json', status_code=200)\n","sub_path":"nuclio/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"599564374","text":"\"\"\" https://leetcode.com/problems/destroy-sequential-targets/\ncount x%space\n\"\"\"\nfrom header import *\n\nclass Solution:\n def destroyTargets(self, A: List[int], space: int) -> int:\n cnt = defaultdict(list)\n for x in A:\n cnt[x%space].append(x)\n \n mx = len(max(cnt.values(), key=len))\n ans = inf\n for k, v in cnt.items():\n if len(v)==mx:\n ans = min(ans, min(v))\n return ans","sub_path":"B_HashTable/Basic/L0_2453_Destroy_Sequential_Targets.py","file_name":"L0_2453_Destroy_Sequential_Targets.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"620914876","text":"# https://codeforces.com/blog/entry/71146\n# https://leetcode.com/problems/critical-connections-in-a-network/discuss/504797/Python-Find-bridgesarticulation-points-with-detailed-explanation\n\nfrom collections import defaultdict\ndef find_articulation_points(nodeNum, edges):\n # Build the graph first \n def APUtil(u, visited, ap, parent, low, disc,graph,time): \n\n children =0\n\n # Mark the current node as visited and print it \n visited[u]= True\n\n # Initialize discovery time and low value \n disc[u] = time \n low[u] = time \n time += 1\n\n for v in graph[u]: \n # If v is not visited yet, then make it a child of u \n # in DFS tree and recur for it \n if visited[v] == False : \n parent[v] = u \n children += 1\n APUtil(v, visited, ap, parent, low, disc,graph,time) \n\n # Check if the subtree rooted with v has a connection to \n # one of the ancestors of u \n low[u] = min(low[u], low[v]) \n\n # u is an articulation point in following cases \n # (1) u is root of DFS tree and has two or more chilren. \n if parent[u] == -1 and children > 1:\n ap.add(u)\n \n\n #(2) If u is not root and low value of one of its child is more \n # than discovery value of u. \n if parent[u] != -1 and low[v] >= disc[u]: \n ap.add(u) \n \n # Update low value of u for parent function calls \n elif v != parent[u]: \n low[u] = min(low[u], disc[v]) \n return \n\n\n\n graph = defaultdict(list)\n for edge in edges:\n graph[edge[0]].append(edge[1])\n graph[edge[1]].append(edge[0])\n \n\n visited = [False] * nodeNum \n disc = [float(\"Inf\")] * nodeNum \n low = [float(\"Inf\")] * nodeNum \n parent = [-1] * nodeNum \n ap = set() \n time = 0\n\n # Call the recursive helper function \n # to find articulation points \n # in DFS tree rooted with vertex 'i' \n for i in range(nodeNum ): \n if visited[i] == False:\n APUtil(i, visited, ap, parent, low, disc,graph,time) \n return list(ap)\n\n\nprint(find_articulation_points(7, [[0, 1], [0, 2], [1, 3], [2, 3], [2, 5], [5, 6], [3, 4]])) \nprint(find_articulation_points(5, [[0, 1], [1, 2], [3, 1], [4, 1], [4, 3], [2, 0]])) ","sub_path":"Company-Based/amazon/critical_nodes.py","file_name":"critical_nodes.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619540261","text":"# -*- coding: utf-8 -*-\n\n#%% 01. 기본 개념\n'''\nGET : read (데이터를 요청)\nPOST : create (데이터 만들기. 특정데이터를 추가 요청)\nPUT : update (특정 데이터 수정하기)\nDELETE : Delete (특정 데이터 삭제하기)\n'''\n\n''' \nURL 구조\n프로토콜://주소 또는 IP:포트번호/리소스 경로?쿼리스트링\n'''\n\n\n'''\n02. 웹 페이지 접속하기\n03. 응답 객체에서 헤더 정보 가져오기\n04. 헤더정보 for문 이용 가져오기\n05. HTML 코드 보기\n06. HTML 코드 보기 - 한글깨지기 때문에 바이너리 형태로 가져오기\n07. 쿼리 스트링 데이터 만들어 요청\n08. post 요청 보내기 - body에 데이터 추가\n'''\n\n#%% 02. 웹 페이지 접속하기\nimport requests as req\n\nurl = \"https://pjt3591oo.github.io\"\n\nres = req.get(url) # get 요청\nres_post = req.post(url) # post 요청 \n\nprint(req.get(url)) # requests는 요청 후, 응답값을 반환한다.\nprint(res.status_code)\n\n\n#%% 03. 응답 객체에서 헤더 정보 가져오기\nimport requests as req\n\nurl = \"https://pjt3591oo.github.io\"\nres = req.get(url) # get 요청\n\nprint(res)\nprint(res.headers)\n\n#%% 04. 헤더정보 for문 이용 가져오기\nimport requests as req\n\nurl = \"https://pjt3591oo.github.io\"\nres = req.get(url) # get 요청\n\nfor dictn in res.headers:\n print(res.headers[dictn])\n\n# 기타 쿠키를 가져오기 있음.\n\n#%% 05. HTML 코드 보기\nimport requests as rq\n\nurl = \"https://pjt3591oo.github.io\"\nres = req.get(url) # get 요청\n\nprint(res.text)\n\n\n#%% 06. HTML 코드 보기 - 한글깨지기 때문에 바이너리 형태로 가져오기\nimport requests as req\n\nurl = \"https://pjt3591oo.github.io\"\nres = req.get(url) # get 요청\n\nprint(res.content)\n\n# 크롤러를 만들다보면 인코딩의 문제를 겪을 수 있다. 그럴 때 해결 방법이\n# text 속성대신에 content 속성을 사용하는 것이다.\n\n#%% 07. 쿼리 스트링 데이터 만들어 요청\nimport requests as req\nurl = \"https://pjt3591oo.github.io\"\n\nres = rq.get(url, params={\"key1\": \"value1\", \"key2\":\"value2\"})\nprint(res.url)\n\n\n#%% 08. post 요청 보내기 - body에 데이터 추가\n'''\n쿼리 스트링은 params 를 사용하지만, body 데이터를 추가할 때, data를 이용한다.\n'''\n\nimport requests as req\nurl = \"https://pjt3591oo.github.io\"\n\nres = req.post(url, data={\"key1\":\"value1\", \"key2\":\"value2\"})\nprint(res.url)\n\n","sub_path":"PythonWeb/basic01.py","file_name":"basic01.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"489069286","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File name: verify_code.py\n\"\"\"\nCreated on Sat Nov 28 20:14:32 2020\n\n@author: Neo(niu.liu@nju.edu.cn)\n\"\"\"\n\nfrom astropy.table import Table\nimport numpy as np\nimport time\n\n# My modules\nfrom vsh_fit_201128 import vsh_fit\nfrom pmt_convert import st_to_rotgldquad\nfrom generate_test_data import generate_test_sample\n\n# Read the simulated data\nrot_vec = np.array([20, 30, 15])\ngli_vec = np.array([30, 24, 12])\n# qua_vec = np.array([-10, 20, -3, 5, 30, 9, 12, 39, 40, 12])\nqua_vec = np.zeros(10)\npmt_vec = np.concatenate((gli_vec, rot_vec, qua_vec))\ntest_tab = generate_test_sample(int(2e2), pmt_vec)\n\n\n# Transform astropy.Column into np.array and mas -> dex\ndra = np.array(test_tab[\"dra\"])\nddec = np.array(test_tab[\"ddec\"])\nra = np.array(test_tab[\"ra\"])\ndec = np.array(test_tab[\"dec\"])\ndra_err = np.array(test_tab[\"dra_err\"])\nddec_err = np.array(test_tab[\"ddec_err\"])\ndra_ddc_cor = np.array(test_tab[\"dra_ddec_cor\"])\n\nprint(\"# num_iter\"\n \" Glide [dex] \"\n \" Rotation [dex] Time_taken [s]\")\nprint(\"# \"\n \" G1 G2 G3 \"\n \" R1 R2 R3 \")\nprint(\"# \"\n \"----------------------------------------- \"\n \"-----------------------------------------\")\n\nprint(\"#Input \"\n \"{0:4.0f} 0 {1:4.0f} 0 \"\n \"{2:4.0f} 0 {3:4.0f} 0 \"\n \"{4:4.0f} 0 {5:4.0f} 0 \".format(*pmt_vec[:6]))\n\n# Record the start time\ntime_s = time.time()\n\n# DO the LSQ fitting\npmt, err, cor_mat = vsh_fit(\n dra, ddec, dra_err, ddec_err, ra, dec, ra_dc_cor=dra_ddc_cor,\n l_max=2, pos_in_rad=True)\n\n# Record the end time\ntime_d = time.time()\n# Time difference\ntime_delta = time_d - time_s\n\npmt1, err1, cor_mat1 = st_to_rotgldquad(pmt, err, cor_mat)\n\nprint(\" \"\n \"{0:4.0f} {6:4.0f} {1:4.0f} {7:4.0f} \"\n \"{2:4.0f} {8:4.0f} {3:4.0f} {9:4.0f} \"\n \"{4:4.0f} {10:4.0f} {5:4.0f} {11:4.0f} \"\n \"{12:.0f}\".format(*pmt1[:6], *err1[:6], time_delta))\n","sub_path":"src/verify_code.py","file_name":"verify_code.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"272758617","text":"print(\"Bem-Vindo ao Jogo da Forca\")\n\npalavra_secreta = \"goiaba\".upper()\n\nnumero_de_tentativas = 3\nerros = 0\nacertou = False\nletras_utilizadas = []\n\ndef captura_letra():\n letra = input(\"informe uma letra: \")\n return letra.upper()\n\npalavra_apresentada = [\"-\" for letra in palavra_secreta]\nwhile erros < numero_de_tentativas:\n print(\"Situação:\")\n print(palavra_apresentada)\n print(\"Letras utilizadas:\")\n print(letras_utilizadas)\n\n letra = captura_letra()\n print(\"chute: \" + letra)\n letras_utilizadas.append(letra)\n\n if letra in palavra_secreta:\n acertou = True \n for i in range(0, len(palavra_apresentada)):\n if letra == palavra_secreta[i]:\n palavra_apresentada[i] = letra\n else:\n acertou = False\n erros += 1\n\n print(acertou)\n ","sub_path":"jogos/jogo-da-forca/jogo-da-forca.py","file_name":"jogo-da-forca.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"334696413","text":"def encrypt(text):\r\n for i in text:\r\n print(chr(ord(i) + 10), end = '')\r\ndef decrypt(text):\r\n for i in text:\r\n print(chr(ord(i) - 10), end = '')\r\n\r\n\r\ntext = input(\"Введите текст: \")\r\ncrypt = input(\"Зашифровать или расшифровать? \")\r\nif crypt.lower() == 'зашифровать':\r\n encrypt(text)\r\nelif crypt.lower() == 'расшифровать':\r\n decrypt(text)","sub_path":"Pythonicus/l04/my_crypt.py","file_name":"my_crypt.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"2751391","text":"# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nfrom collections import defaultdict\n\nfrom ...operands import ShuffleProxy\nfrom ...errors import WorkerDead\nfrom .base import BaseOperandActor\nfrom .core import register_operand_class, rewrite_worker_errors, OperandState\n\nlogger = logging.getLogger(__name__)\n\n\nclass ShuffleProxyActor(BaseOperandActor):\n def __init__(self, session_id, graph_id, op_key, op_info, **kwargs):\n super().__init__(session_id, graph_id, op_key, op_info, **kwargs)\n self._session_id = session_id\n self._graph_id = graph_id\n self._op_key = op_key\n\n io_meta = self._io_meta\n self._shuffle_keys_to_op = dict(zip(io_meta['shuffle_keys'], io_meta['successors']))\n self._op_to_shuffle_keys = dict(zip(io_meta['successors'], io_meta['shuffle_keys']))\n\n self._worker_to_mappers = defaultdict(set)\n self._reducer_workers = dict()\n\n self._all_deps_built = False\n self._mapper_op_to_chunk = dict()\n self._reducer_to_mapper = defaultdict(dict)\n\n def add_finished_predecessor(self, op_key, worker, output_sizes=None, output_shapes=None):\n super().add_finished_predecessor(op_key, worker, output_sizes=output_sizes,\n output_shapes=output_shapes)\n\n from ..chunkmeta import WorkerMeta\n chunk_key = next(iter(output_sizes.keys()))[0]\n self._mapper_op_to_chunk[op_key] = chunk_key\n if op_key not in self._worker_to_mappers[worker]:\n self._worker_to_mappers[worker].add(op_key)\n self.chunk_meta.add_worker(self._session_id, chunk_key, worker, _tell=True)\n\n shuffle_keys_to_op = self._shuffle_keys_to_op\n\n if not self._reducer_workers:\n self._reducer_workers = self._graph_refs[0].assign_operand_workers(\n self._succ_keys, input_chunk_metas=self._reducer_to_mapper)\n reducer_workers = self._reducer_workers\n data_to_addresses = dict()\n\n unused_keys = []\n\n for (chunk_key, shuffle_key), data_size in output_sizes.items() or ():\n if shuffle_key not in shuffle_keys_to_op:\n # outputs may be pruned, hence those keys become useless\n unused_keys.append((chunk_key, shuffle_key))\n continue\n\n succ_op_key = shuffle_keys_to_op[shuffle_key]\n meta = self._reducer_to_mapper[succ_op_key][op_key] = \\\n WorkerMeta(chunk_size=data_size, workers=(worker,),\n chunk_shape=output_shapes.get((chunk_key, shuffle_key)))\n reducer_worker = reducer_workers.get(succ_op_key)\n if reducer_worker and reducer_worker != worker:\n data_to_addresses[(chunk_key, shuffle_key)] = [reducer_worker]\n meta.workers += (reducer_worker,)\n\n if unused_keys:\n self._free_data_in_worker(unused_keys, [(worker,)] * len(unused_keys))\n\n if data_to_addresses:\n try:\n with rewrite_worker_errors():\n self._get_raw_execution_ref(address=worker) \\\n .send_data_to_workers(self._session_id, data_to_addresses, _tell=True)\n except WorkerDead:\n self._resource_ref.detach_dead_workers([worker], _tell=True)\n\n if all(k in self._finish_preds for k in self._pred_keys):\n self._start_successors()\n\n def append_graph(self, graph_key, op_info):\n super().append_graph(graph_key, op_info)\n\n io_meta = op_info['io_meta']\n self._shuffle_keys_to_op = dict(zip(io_meta['shuffle_keys'], io_meta['successors']))\n self._op_to_shuffle_keys = dict(zip(io_meta['successors'], io_meta['shuffle_keys']))\n\n def _start_successors(self):\n self._all_deps_built = True\n futures = []\n\n logger.debug('Predecessors of shuffle proxy %s done, notifying successors', self._op_key)\n for succ_key in self._succ_keys:\n if succ_key in self._finish_succs:\n continue\n\n shuffle_key = self._op_to_shuffle_keys[succ_key]\n input_data_metas = dict(((self._mapper_op_to_chunk[k], shuffle_key), meta)\n for k, meta in self._reducer_to_mapper[succ_key].items())\n\n futures.append(self._get_operand_actor(succ_key).start_operand(\n OperandState.READY, io_meta=dict(input_data_metas=input_data_metas),\n target_worker=self._reducer_workers.get(succ_key),\n _tell=True, _wait=False))\n\n [f.result() for f in futures]\n self.ref().start_operand(OperandState.FINISHED, _tell=True)\n\n def add_finished_successor(self, op_key, worker):\n super().add_finished_successor(op_key, worker)\n shuffle_key = self._op_to_shuffle_keys[op_key]\n\n # input data in reduce nodes can be freed safely\n data_keys = []\n workers_list = []\n for pred_key, meta in self._reducer_to_mapper[op_key].items():\n data_keys.append((self._mapper_op_to_chunk[pred_key], shuffle_key))\n workers_list.append((self._reducer_workers[op_key],))\n self._free_data_in_worker(data_keys, workers_list)\n\n if all(k in self._finish_succs for k in self._succ_keys):\n self.free_predecessors()\n\n def free_predecessors(self):\n can_be_freed, deterministic = self.check_can_be_freed()\n if not deterministic:\n # if we cannot determine whether to do failover, just delay and retry\n self.ref().free_predecessors(_delay=1, _tell=True)\n return\n elif not can_be_freed:\n return\n\n futures = []\n for k in self._pred_keys:\n futures.append(self._get_operand_actor(k).start_operand(\n OperandState.FREED, _tell=True, _wait=False))\n\n data_keys = []\n workers_list = []\n for op_key in self._succ_keys:\n shuffle_key = self._op_to_shuffle_keys[op_key]\n for pred_key, meta in self._reducer_to_mapper[op_key].items():\n data_keys.append((self._mapper_op_to_chunk[pred_key], shuffle_key))\n workers_list.append(tuple(set(meta.workers + (self._reducer_workers[op_key],))))\n self._free_data_in_worker(data_keys, workers_list)\n\n inp_chunk_keys = [self._mapper_op_to_chunk[k] for k in self._pred_keys\n if k in self._mapper_op_to_chunk]\n self.chunk_meta.batch_delete_meta(\n self._session_id, inp_chunk_keys, _tell=True, _wait=False)\n self._finish_preds = set()\n [f.result() for f in futures]\n\n self.ref().start_operand(OperandState.FREED, _tell=True)\n\n def update_demand_depths(self, depth):\n pass\n\n def propose_descendant_workers(self, input_key, worker_scores, depth=1):\n pass\n\n def move_failover_state(self, from_states, state, new_target, dead_workers):\n if self.state not in from_states:\n return\n\n dead_workers = set(dead_workers)\n for w in dead_workers:\n self._finish_preds.difference_update(self._worker_to_mappers[w])\n del self._worker_to_mappers[w]\n\n for op_key in self._succ_keys:\n if op_key not in self._reducer_to_mapper:\n continue\n new_mapper_metas = dict()\n for pred_key, meta in self._reducer_to_mapper[op_key].items():\n meta.workers = tuple(w for w in meta.workers if w not in dead_workers)\n if meta.workers:\n new_mapper_metas[pred_key] = meta\n self._reducer_to_mapper[op_key] = new_mapper_metas\n\n missing_succs = []\n for op, w in self._reducer_workers.items():\n if w in dead_workers:\n missing_succs.append(op)\n self._finish_succs.difference_update(missing_succs)\n\n if missing_succs:\n self._reducer_workers.update(self._graph_refs[0].assign_operand_workers(\n missing_succs, input_chunk_metas=self._reducer_to_mapper))\n\n super().move_failover_state(\n from_states, state, new_target, dead_workers)\n\n def free_data(self, state=OperandState.FREED, check=True):\n pass\n\n def _on_cancelling(self):\n futures = []\n for k in self._succ_keys:\n futures.append(self._get_operand_actor(k).stop_operand(\n OperandState.CANCELLING, _tell=True, _wait=False))\n [f.result() for f in futures]\n self.start_operand(OperandState.CANCELLED)\n\n def _on_fatal(self):\n if self._last_state == OperandState.FATAL:\n return\n futures = []\n # set successors to FATAL\n for k in self._succ_keys:\n futures.append(self._get_operand_actor(k).stop_operand(\n OperandState.FATAL, _tell=True, _wait=False))\n [f.result() for f in futures]\n\n\nregister_operand_class(ShuffleProxy, ShuffleProxyActor)\n","sub_path":"mars/scheduler/operands/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":9499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"360312977","text":"import calendar as cld, datetime as dt\nimport pandas as pd\nfrom utils.algorithm import preprocess as pre, calculation as cal\nfrom utils.database import config as cfg, io\nfrom utils.dev import calargs\n\ntoday = dt.date.today()\nlast_month = today - dt.timedelta(today.day)\n\nengines = cfg.load_engine()\nengine_rd = engines[\"2Gb\"]\ntoday = dt.date.today()\n\n_freq = \"m\"\n_intervals = calargs.intervals\n\n_funcs_return = [\n \"accumulative_return\", \"return_a\", \"sharpe_a\", \"calmar_a\", \"sortino_a\"\n]\n\n_funcs_risk = [\n \"stdev\", \"stdev_a\", \"downside_deviation_a\", \"max_drawdown\"\n]\n\n_funcs_sub = [\n \"con_rise_periods\", \"con_fall_periods\", \"VaR\", \"p_earning_periods\", \"n_earning_periods\", \"min_return\", \"max_return\", \"mdd_repair_time\",\n \"mdd_time\", \"skewness\", \"kurtosis\", \"ERVaR\"\n]\n\n\nfor year in range(last_month.year, last_month.year + 1):\n for month in range(last_month.month, last_month.month + 1):\n month_range = cld.monthrange(year, month)[1]\n for day in range(month_range, month_range + 1):\n result_return = []\n result_risk = []\n result_sub = []\n\n statistic_date = dt.date(year, month, day)\n ids_used = pre.fetch_fids_used(statistic_date=statistic_date, freq=_freq, conn=engine_rd)\n\n data = pre.ProcessedData(statistic_date, [], _freq)\n bms = {index_id: cal.Benchmark(attr_dict, index_id) for index_id, attr_dict in data.index.items()}\n tbond = cal.Tbond(data.index[\"y1_treasury_rate\"], \"y1_treasury_rate\")\n\n for bm_name, bm in bms.items():\n if bm.id == \"y1_treasury_rate\":\n continue\n\n res_return, funcs_return_sorted = cal.calculate(_funcs_return, _intervals, None, _freq, statistic_date, bm, None, tbond, with_func_names=True)\n res_risk, funcs_risk_sorted = cal.calculate(_funcs_risk, _intervals, None, _freq, statistic_date, bm, None, tbond, with_func_names=True)\n res_sub, funcs_sub_sorted = cal.calculate(_funcs_sub, _intervals, None, _freq, statistic_date, bm, None, tbond, with_func_names=True)\n\n result_return.extend(res_return)\n result_risk.extend(res_risk)\n result_sub.extend(res_sub)\n\n df_return = pd.DataFrame(result_return)\n df_risk = pd.DataFrame(result_risk)\n df_sub = pd.DataFrame(result_sub)\n\n cols_return = cal.format_cols(funcs_return_sorted, _freq, prefix=[\"index_id\", \"index_name\", \"statistic_date\"])\n cols_risk = cal.format_cols(funcs_risk_sorted, _freq, prefix=[\"index_id\", \"index_name\", \"statistic_date\"])\n cols_sub = cal.format_cols(funcs_sub_sorted, _freq, prefix=[\"index_id\", \"index_name\", \"statistic_date\"])\n\n df_return.columns = cols_return\n df_risk.columns = cols_risk\n df_sub.columns = cols_sub\n df_return[\"index_id\"] = df_return[\"index_id\"].apply(str.upper)\n df_risk[\"index_id\"] = df_risk[\"index_id\"].apply(str.upper)\n df_sub[\"index_id\"] = df_sub[\"index_id\"].apply(str.upper)\n\n io.to_sql(\"index_monthly_return\", conn=engine_rd, dataframe=df_return, chunksize=5000)\n io.to_sql(\"index_monthly_risk\", conn=engine_rd, dataframe=df_risk, chunksize=5000)\n io.to_sql(\"index_monthly_subsidiary\", conn=engine_rd, dataframe=df_sub, chunksize=5000)\n\n# res_return = cal.calculate(_funcs_return, _intervals, _bms_used, _freq, statistic_date, fund, bms, tbond)\n# res_risk = cal.calculate(_funcs_risk, _intervals, _bms_used, _freq, statistic_date, fund, bms, tbond)\n# res_sub = cal.calculate(_funcs_sub, _intervals, _bms_used, _freq, statistic_date, fund, bms, tbond)\n# result_return.extend(res_return)\n# result_risk.extend(res_risk)\n# result_sub.extend(res_sub)\n\n# df_return = pd.DataFrame(result_return)\n# df_risk = pd.DataFrame(result_risk)\n# df_sub = pd.DataFrame(result_sub)\n#\n# df_return.columns = cols_return\n# df_risk.columns = cols_risk\n# df_sub.columns = cols_sub","sub_path":"SCRIPT/PRIVATE/cal/index_monthly_indicator/script_bm_m.py","file_name":"script_bm_m.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"319709319","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nimport time\n\ndef isHangul(text):\n encText = text\n hanCount = len(re.findall(u'[\\u3130-\\u318F\\uAC00-\\uD7A3]+', encText))\n return hanCount > 0\n\ndef check_latest_update():\n url = 'http://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu4&page_num=20&category=&search_type=sub_memo&keyword=%C4%B7%C7%CE'\n html = requests.get(url).text\n soup = BeautifulSoup(html, 'html.parser')\n\n latest_update = soup.find(\"tr\", {\"class\": \"list1\"}).find(\"nobr\", {\"class\": \"eng list_vspace\"}).get_text()\n latest_update = latest_update.replace(\"/\", \"-\")\n current_day = str(datetime.today().year) + \"-\" + str(datetime.today().month) + \"-\" + str(datetime.today().day)\n\n if (\":\" in latest_update):\n latest_update = current_day + \" \" + latest_update\n\n print(\"*** latest_update: \" + latest_update + \" ***\");\n \n return latest_update\n\ndef check_crawling_target(a_tag, latest_update):\n temp_date = a_tag.find(\"nobr\", {\"class\": \"eng list_vspace\"}).get_text()\n temp_date = temp_date.replace(\"/\", \"-\")\n current_day = str(datetime.today().year) + \"-\" + str(datetime.today().month) + \"-\" + str(datetime.today().day)\n\n if (\":\" in temp_date):\n temp_date = current_day + \" \" + temp_date\n\n print(temp_date)\n\n # latest_update < temp_date\n if (latest_update\", \"\")\n current_list_title = current_list_title.replace(\"\", \"\")\n\n price_index = current_list_title.rfind(\"(\") + 1\n temp_string = current_list_title[price_index:]\n temp_index = temp_string.find(\"/\")\n price_string = temp_string[:temp_index]\n\n print(temp_string[:temp_index] + \"\\n\")\n\n\nif __name__ == '__main__':\n\n latest_update=check_latest_update()\n\n while(1):\n print(\"\\n-체크-\")\n\n url = 'http://www.ppomppu.co.kr/zboard/zboard.php?id=ppomppu4&page_num=20&category=&search_type=sub_memo&keyword=%C4%B7%C7%CE'\n html = requests.get(url).text\n soup = BeautifulSoup(html, 'html.parser')\n\n for a_tag in soup.select('.list0'):\n check_crawling_target(a_tag,latest_update)\n\n for a_tag in soup.select('.list1'):\n check_crawling_target(a_tag, latest_update)\n\n latest_update = check_latest_update()\n time.sleep(300)\n\n\n","sub_path":"ppomppu_crawling/ppomppu.py","file_name":"ppomppu.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"513234656","text":"#This implementation shows the minimum number of stops that the salesman must take\r\n#It does not take the distance into consideration\r\n#This is a strict implementation of the BFS algorithm\r\n\r\n#Import Libraries\r\nfrom collections import deque\r\nimport math\r\nfrom matplotlib import style \r\nimport matplotlib.pyplot as plt \r\n\r\n#Initialize variables\r\nx = []\r\ny = []\r\nqueue = deque()\r\n\r\n#Used to store which cities are reachable from each city\r\ncityGraph = { \r\n 1 : [2, 3, 4],\r\n 2 : [3],\r\n 3 : [4, 5],\r\n 4 : [5, 6, 7],\r\n 5 : [7, 8],\r\n 6 : [8],\r\n 7 : [9, 10],\r\n 8 : [9, 10, 11],\r\n 9 : [11],\r\n 10 : [11],\r\n 11 : []\r\n }\r\n\r\n############################################################################\r\ndef read_datafile(path):\r\n #Import data file\r\n i = 0\r\n x = []\r\n y = []\r\n with open((path), \"r\") as file:\r\n for line in file:\r\n split_line = line.strip().split(\" \")\r\n \r\n #Track line number to remove header info\r\n if i > 6:\r\n #Populate x,y coordinate pairs into arrays\r\n x.append(float(split_line[1]))\r\n y.append(float(split_line[2]))\r\n #increment line counter\r\n i += 1 \r\n return x, y\r\n########################################\r\n#graph sets of xy coordinates\r\ndef graph_coords(x, y, x2, y2, min_dist):\r\n #Define graph style\r\n style.use('dark_background')\r\n \r\n # plotting the points\r\n plt.plot(x, y,'ro', label=\"Non-Visited Vertices\")\r\n plt.plot(x2, y2,'yo-', label=\"Optimum Path\")\r\n for i in range(len(x2)):\r\n plt.annotate((len(x2) - (i + 1)), (x2[i], y2[i]), textcoords=\"offset points\", xytext=(0,5), ha = 'center')\r\n \r\n # naming the axes \r\n plt.xlabel('x - axis') \r\n plt.ylabel('y - axis') \r\n plt.legend()\r\n # giving a title to my graph \r\n plt.title((\"Optimum Stops: \" + str(min_dist)))\r\n \r\n # function to show the plot \r\n plt.pause(.05)\r\n plt.show() \r\n\r\n return\r\n \r\n########################################\r\ndef BFS(queue): #queue is a queue of pointers to city objects\r\n found = False\r\n while(queue):\r\n currCity = queue.popleft()\r\n \r\n #print(currCity.name)\r\n \r\n \r\n for city in currCity.cities: #Grab left most element from queue\r\n if(not(cityArr[city - 1].visited)): #else already queued\r\n cityArr[city - 1].visited = True #Mark that node is already in queue\r\n cityArr[city - 1].distance = currCity.distance + 1 #Set distance to 1 more than previous cities distance\r\n cityArr[city - 1].previous = currCity.name\r\n \r\n queue.append(cityArr[city -1]) #Add city to queue\r\n \r\n if((city) == 11):\r\n found = True\r\n break\r\n if(found):\r\n return \r\n########################################\r\ndef backtrack(cityArr):\r\n i = 11\r\n out = []\r\n out.append(i)\r\n \r\n xcoords = []\r\n xcoords.append(cityArr[i - 1].x)\r\n ycoords = []\r\n ycoords.append(cityArr[i - 1].y)\r\n \r\n while(cityArr[i - 1].previous != 0): \r\n i = cityArr[i - 1].previous\r\n out.append(i)\r\n xcoords.append(cityArr[i - 1].x)\r\n ycoords.append(cityArr[i - 1].y)\r\n \r\n return xcoords, ycoords, out \r\n\r\n########################################\r\nclass city():\r\n def __init__(self, name, x, y, cities):\r\n self.name = name\r\n self.x = x\r\n self.y = y\r\n self.cities = cities\r\n self.visited = False\r\n self.previous = 0\r\n self.distance = math.inf\r\n############################################################################\r\n\r\n#######\r\n#INPUT\r\n######\r\n \r\n#data file path\r\nfile_path = str(r'C:\\Users\\burkh\\OneDrive\\Desktop\\AI\\Project2\\nodes.tsp')\r\n#used to read and parse the tsp file\r\nx, y = read_datafile(file_path)\r\n\r\n#############\r\n#FORMAT DATA\r\n############\r\n\r\n#Initalize and store array of cities\r\ncityArr = []\r\nfor i in range(11):\r\n c = city(i+1, x[i], y[i], cityGraph[i+1])\r\n cityArr.append(c)\r\n\r\n############\r\n#PROCESSING\r\n###########\r\n \r\n#Initalize Queue with first city\r\ncityArr[0].visited = True\r\ncityArr[0].distance = 0\r\nqueue.append(cityArr[0]) #Starting at node 1 = cityArr[0]\r\n\r\n#Run BFS to update city array\r\nBFS(queue)\r\n\r\n\r\n########\r\n#OUTPUT\r\n#######\r\n \r\n#list path taken\r\nxcoords, ycoords, path = backtrack(cityArr)\r\n\r\n#Graph Path/ Unused Points\r\ngraph_coords(x, y, xcoords, ycoords, cityArr[10].distance)\r\n\r\nprint(\"Distance to city 11: \" + str(cityArr[10].distance))\r\nprint(\"Path: \" + str((path)).strip('[]'))\r\n","sub_path":"BFS_Strict.py","file_name":"BFS_Strict.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"397352864","text":"#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# pylint: disable=not-callable, line-too-long, no-else-return\n\nimport argparse\nimport glob\nimport logging\nfrom pathlib import Path\nimport os\nimport shutil\nimport string\nimport sys\nimport textwrap\nfrom typing import Dict, List, Optional, Set\n\nimport android_version\nimport builders\nfrom builder_registry import BuilderRegistry\nimport configs\nimport constants\nimport hosts\nimport paths\nimport source_manager\nimport toolchains\nimport utils\nfrom version import Version\n\nimport mapfile\n\nORIG_ENV = dict(os.environ)\n\n# Remove GOMA from our environment for building anything from stage2 onwards,\n# since it is using a non-GOMA compiler (from stage1) to do the compilation.\nUSE_GOMA_FOR_STAGE1 = False\nif ('USE_GOMA' in ORIG_ENV) and (ORIG_ENV['USE_GOMA'] == 'true'):\n USE_GOMA_FOR_STAGE1 = True\n del ORIG_ENV['USE_GOMA']\n\nBASE_TARGETS = 'AArch64'\nANDROID_TARGETS = 'AArch64;ARM;BPF;X86'\n\n# TODO (Pirama): Put all the build options in a global so it's easy to refer to\n# them instead of plumbing flags through function parameters.\nBUILD_LLDB = False\nBUILD_LLVM_NEXT = False\n\ndef logger():\n \"\"\"Returns the module level logger.\"\"\"\n return logging.getLogger(__name__)\n\n\ndef install_file(src, dst):\n \"\"\"Proxy for shutil.copy2 with logging and dry-run support.\"\"\"\n logger().info('copy %s %s', src, dst)\n shutil.copy2(src, dst)\n\n\ndef remove(path):\n \"\"\"Proxy for os.remove with logging.\"\"\"\n logger().debug('remove %s', path)\n os.remove(path)\n\n\ndef extract_clang_version(clang_install) -> Version:\n version_file = (Path(clang_install) / 'include' / 'clang' / 'Basic' /\n 'Version.inc')\n return Version(version_file)\n\n\ndef pgo_profdata_filename():\n svn_revision = android_version.get_svn_revision(BUILD_LLVM_NEXT)\n base_revision = svn_revision.rstrip(string.ascii_lowercase)\n return '%s.profdata' % base_revision\n\ndef pgo_profdata_file(profdata_file):\n profile = utils.android_path('prebuilts', 'clang', 'host', 'linux-x86',\n 'profiles', profdata_file)\n return profile if os.path.exists(profile) else None\n\n\ndef ndk_base():\n ndk_version = 'r20'\n return utils.android_path('toolchain/prebuilts/ndk', ndk_version)\n\n\ndef android_api(arch: hosts.Arch, platform=False):\n if platform:\n return 29\n elif arch in [hosts.Arch.ARM, hosts.Arch.I386]:\n return 16\n else:\n return 21\n\n\ndef ndk_libcxx_headers():\n return os.path.join(ndk_base(), 'sources', 'cxx-stl', 'llvm-libc++',\n 'include')\n\n\ndef ndk_libcxxabi_headers():\n return os.path.join(ndk_base(), 'sources', 'cxx-stl', 'llvm-libc++abi',\n 'include')\n\n\ndef ndk_toolchain_lib(arch: hosts.Arch, toolchain_root, host_tag):\n toolchain_lib = os.path.join(ndk_base(), 'toolchains', toolchain_root,\n 'prebuilt', 'linux-x86_64', host_tag)\n if arch in [hosts.Arch.ARM, hosts.Arch.I386]:\n toolchain_lib = os.path.join(toolchain_lib, 'lib')\n else:\n toolchain_lib = os.path.join(toolchain_lib, 'lib64')\n return toolchain_lib\n\n\ndef support_headers():\n return os.path.join(ndk_base(), 'sources', 'android', 'support', 'include')\n\n\ndef clang_prebuilt_base_dir():\n return utils.android_path('prebuilts/clang/host',\n hosts.build_host().os_tag, constants.CLANG_PREBUILT_VERSION)\n\n\ndef clang_prebuilt_bin_dir():\n return utils.android_path(clang_prebuilt_base_dir(), 'bin')\n\n\ndef clang_resource_dir(version, arch: Optional[hosts.Arch] = None):\n arch_str = arch.value if arch else ''\n #return os.path.join('lib64', 'clang', version, 'lib', 'linux', arch_str)\n return os.path.join('lib64', 'clang', version, 'lib', 'android', arch_str)\n\n\ndef clang_prebuilt_libcxx_headers():\n return utils.android_path(clang_prebuilt_base_dir(), 'include', 'c++', 'v1')\n\n\ndef libcxx_header_dirs(ndk_cxx):\n if ndk_cxx:\n return [\n ndk_libcxx_headers(),\n ndk_libcxxabi_headers(),\n support_headers()\n ]\n else:\n # /include/c++/v1 includes the cxxabi headers\n return [\n clang_prebuilt_libcxx_headers(),\n utils.android_path('bionic', 'libc', 'include')\n ]\n\n\ndef cmake_bin_path():\n return utils.android_path('prebuilts/cmake', hosts.build_host().os_tag, 'bin/cmake')\n\n\ndef ninja_bin_path():\n return utils.android_path('prebuilts/ninja', hosts.build_host().os_tag, 'ninja')\n\n\ndef check_create_path(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef get_sysroot(arch: hosts.Arch, platform=False):\n sysroots = utils.out_path('sysroots')\n platform_or_ndk = 'platform' if platform else 'ndk'\n return os.path.join(sysroots, platform_or_ndk, arch.ndk_arch)\n\n\ndef debug_prefix_flag():\n return '-fdebug-prefix-map={}='.format(utils.android_path())\n\n\ndef go_bin_dir():\n return utils.android_path('prebuilts/go', hosts.build_host().os_tag, 'bin')\n\n\ndef create_sysroots():\n # Construct the sysroots from scratch, since symlinks can't nest within\n # the right places (without altering source prebuilts).\n configs = [\n (hosts.Arch.ARM, 'arm-linux-androideabi'),\n (hosts.Arch.AARCH64, 'aarch64-linux-android'),\n (hosts.Arch.X86_64, 'x86_64-linux-android'),\n (hosts.Arch.I386, 'i686-linux-android'),\n ]\n\n # TODO(srhines): We destroy and recreate the sysroots each time, but this\n # could check for differences and only replace files if needed.\n sysroots_out = utils.out_path('sysroots')\n if os.path.exists(sysroots_out):\n shutil.rmtree(sysroots_out)\n check_create_path(sysroots_out)\n\n base_header_path = os.path.join(ndk_base(), 'sysroot', 'usr', 'include')\n for (arch, target) in configs:\n # Also create sysroots for each of platform and the NDK.\n for platform_or_ndk in ['platform', 'ndk']:\n platform = platform_or_ndk == 'platform'\n base_lib_path = \\\n utils.android_path(ndk_base(), 'platforms',\n 'android-' + str(android_api(arch, platform)))\n dest_usr = os.path.join(get_sysroot(arch, platform), 'usr')\n\n # Copy over usr/include.\n dest_usr_include = os.path.join(dest_usr, 'include')\n shutil.copytree(base_header_path, dest_usr_include, symlinks=True)\n\n # Copy over usr/include/asm.\n asm_headers = os.path.join(base_header_path, target, 'asm')\n dest_usr_include_asm = os.path.join(dest_usr_include, 'asm')\n shutil.copytree(asm_headers, dest_usr_include_asm, symlinks=True)\n\n # Copy over usr/lib.\n arch_lib_path = os.path.join(base_lib_path, 'arch-' + arch.ndk_arch,\n 'usr', 'lib')\n dest_usr_lib = os.path.join(dest_usr, 'lib')\n shutil.copytree(arch_lib_path, dest_usr_lib, symlinks=True)\n\n # For only x86_64, we also need to copy over usr/lib64\n if arch == hosts.Arch.X86_64:\n arch_lib64_path = os.path.join(base_lib_path, 'arch-' + arch.ndk_arch,\n 'usr', 'lib64')\n dest_usr_lib64 = os.path.join(dest_usr, 'lib64')\n shutil.copytree(arch_lib64_path, dest_usr_lib64, symlinks=True)\n\n if platform:\n # Create a stub library for the platform's libc++.\n platform_stubs = utils.out_path('platform_stubs', arch.ndk_arch)\n check_create_path(platform_stubs)\n libdir = dest_usr_lib64 if arch == hosts.Arch.X86_64 else dest_usr_lib\n with open(os.path.join(platform_stubs, 'libc++.c'), 'w') as f:\n f.write(textwrap.dedent(\"\"\"\\\n void __cxa_atexit() {}\n void __cxa_demangle() {}\n void __cxa_finalize() {}\n void __dynamic_cast() {}\n void _ZTIN10__cxxabiv117__class_type_infoE() {}\n void _ZTIN10__cxxabiv120__si_class_type_infoE() {}\n void _ZTIN10__cxxabiv121__vmi_class_type_infoE() {}\n void _ZTISt9type_info() {}\n \"\"\"))\n utils.check_call([utils.out_path('stage2-install', 'bin', 'clang'),\n '--target=' + target,\n '-fuse-ld=lld', '-nostdlib', '-shared',\n '-Wl,-soname,libc++.so',\n '-o', os.path.join(libdir, 'libc++.so'),\n os.path.join(platform_stubs, 'libc++.c')])\n\n # For arm64 and x86_64, build static cxxabi library from\n # toolchain/libcxxabi and use it when building runtimes. This\n # should affect all compiler-rt runtimes that use libcxxabi\n # (e.g. asan, hwasan, scudo, tsan, ubsan, xray).\n if arch not in (hosts.Arch.AARCH64, hosts.Arch.X86_64):\n with open(os.path.join(libdir, 'libc++abi.so'), 'w') as f:\n f.write('INPUT(-lc++)')\n else:\n # We can build libcxxabi only after the sysroots are\n # created. Build it for the current arch and copy it to\n # .\n out_dir = build_libcxxabi(utils.out_path('stage2-install'), arch)\n out_path = utils.out_path(out_dir, 'lib64', 'libc++abi.a')\n shutil.copy2(out_path, os.path.join(libdir))\n\n\ndef update_cmake_sysroot_flags(defines, sysroot):\n defines['CMAKE_SYSROOT'] = sysroot\n defines['CMAKE_FIND_ROOT_PATH_MODE_INCLUDE'] = 'ONLY'\n defines['CMAKE_FIND_ROOT_PATH_MODE_LIBRARY'] = 'ONLY'\n defines['CMAKE_FIND_ROOT_PATH_MODE_PACKAGE'] = 'ONLY'\n defines['CMAKE_FIND_ROOT_PATH_MODE_PROGRAM'] = 'NEVER'\n\n\ndef rm_cmake_cache(cacheDir):\n for dirpath, dirs, files in os.walk(cacheDir): # pylint: disable=not-an-iterable\n if 'CMakeCache.txt' in files:\n os.remove(os.path.join(dirpath, 'CMakeCache.txt'))\n if 'CMakeFiles' in dirs:\n utils.rm_tree(os.path.join(dirpath, 'CMakeFiles'))\n\n\n# Base cmake options such as build type that are common across all invocations\ndef base_cmake_defines():\n defines = {}\n\n defines['CMAKE_BUILD_TYPE'] = 'Release'\n defines['LLVM_ENABLE_ASSERTIONS'] = 'OFF'\n # https://github.com/android-ndk/ndk/issues/574 - Don't depend on libtinfo.\n defines['LLVM_ENABLE_TERMINFO'] = 'OFF'\n defines['LLVM_ENABLE_THREADS'] = 'ON'\n defines['LLVM_USE_NEWPM'] = 'ON'\n defines['LLVM_LIBDIR_SUFFIX'] = '64'\n defines['LLVM_VERSION_PATCH'] = android_version.patch_level\n defines['CLANG_VERSION_PATCHLEVEL'] = android_version.patch_level\n defines['CLANG_REPOSITORY_STRING'] = 'https://android.googlesource.com/toolchain/llvm-project'\n defines['BUG_REPORT_URL'] = 'https://github.com/android-ndk/ndk/issues'\n\n if hosts.build_host().is_darwin:\n # This will be used to set -mmacosx-version-min. And helps to choose SDK.\n # To specify a SDK, set CMAKE_OSX_SYSROOT or SDKROOT environment variable.\n defines['CMAKE_OSX_DEPLOYMENT_TARGET'] = constants.MAC_MIN_VERSION\n\n # http://b/111885871 - Disable building xray because of MacOS issues.\n defines['COMPILER_RT_BUILD_XRAY'] = 'OFF'\n return defines\n\n\ndef invoke_cmake(out_path, defines, env, cmake_path, target=None, install=True):\n flags = ['-G', 'Ninja']\n\n flags += ['-DCMAKE_MAKE_PROGRAM=' + ninja_bin_path()]\n\n for key in defines:\n newdef = '-D' + key + '=' + defines[key]\n flags += [newdef]\n flags += [cmake_path]\n\n check_create_path(out_path)\n # TODO(srhines): Enable this with a flag, because it forces clean builds\n # due to the updated cmake generated files.\n #rm_cmake_cache(out_path)\n\n if target:\n ninja_target = [target]\n else:\n ninja_target = []\n\n utils.check_call([cmake_bin_path()] + flags, cwd=out_path, env=env)\n utils.check_call([ninja_bin_path()] + ninja_target, cwd=out_path, env=env)\n if install:\n utils.check_call([ninja_bin_path(), 'install'], cwd=out_path, env=env)\n\n\ndef cross_compile_configs(toolchain, platform=False, static=False):\n configs = [\n (hosts.Arch.ARM, 'arm/arm-linux-androideabi-4.9/arm-linux-androideabi',\n 'arm-linux-android', '-march=armv7-a'),\n (hosts.Arch.AARCH64,\n 'aarch64/aarch64-linux-android-4.9/aarch64-linux-android',\n 'aarch64-linux-android', ''),\n (hosts.Arch.X86_64,\n 'x86/x86_64-linux-android-4.9/x86_64-linux-android',\n 'x86_64-linux-android', ''),\n (hosts.Arch.I386, 'x86/x86_64-linux-android-4.9/x86_64-linux-android',\n 'i686-linux-android', '-m32'),\n ]\n\n cc = os.path.join(toolchain, 'bin', 'clang')\n cxx = os.path.join(toolchain, 'bin', 'clang++')\n llvm_config = os.path.join(toolchain, 'bin', 'llvm-config')\n\n for (arch, toolchain_path, llvm_triple, extra_flags) in configs:\n if static:\n api_level = android_api(arch, platform=True)\n else:\n api_level = android_api(arch, platform)\n toolchain_root = utils.android_path('prebuilts/gcc',\n hosts.build_host().os_tag)\n toolchain_bin = os.path.join(toolchain_root, toolchain_path, 'bin')\n sysroot = get_sysroot(arch, platform)\n\n defines = {}\n defines['CMAKE_C_COMPILER'] = cc\n defines['CMAKE_CXX_COMPILER'] = cxx\n defines['LLVM_CONFIG_PATH'] = llvm_config\n\n # Include the directory with libgcc.a to the linker search path.\n toolchain_builtins = os.path.join(\n toolchain_root, toolchain_path, '..', 'lib', 'gcc',\n os.path.basename(toolchain_path), '4.9.x')\n # The 32-bit libgcc.a is sometimes in a separate subdir\n if arch == hosts.Arch.I386:\n toolchain_builtins = os.path.join(toolchain_builtins, '32')\n\n if arch == hosts.Arch.ARM:\n toolchain_lib = ndk_toolchain_lib(arch, 'arm-linux-androideabi-4.9',\n 'arm-linux-androideabi')\n elif arch in [hosts.Arch.I386, hosts.Arch.X86_64]:\n toolchain_lib = ndk_toolchain_lib(arch, arch.ndk_arch + '-4.9',\n llvm_triple)\n else:\n toolchain_lib = ndk_toolchain_lib(arch, llvm_triple + '-4.9',\n llvm_triple)\n\n ldflags = [\n '-L' + toolchain_builtins, '-Wl,-z,defs',\n '-L' + toolchain_lib,\n '-fuse-ld=lld',\n '-Wl,--gc-sections',\n '-Wl,--build-id=sha1',\n '-pie',\n ]\n if static:\n ldflags.append('-static')\n if not platform:\n triple = 'arm-linux-androideabi' if arch == hosts.Arch.ARM else llvm_triple\n libcxx_libs = os.path.join(ndk_base(), 'toolchains', 'llvm',\n 'prebuilt', 'linux-x86_64', 'sysroot',\n 'usr', 'lib', triple)\n ldflags += ['-L', os.path.join(libcxx_libs, str(api_level))]\n ldflags += ['-L', libcxx_libs]\n\n defines['CMAKE_EXE_LINKER_FLAGS'] = ' '.join(ldflags)\n defines['CMAKE_SHARED_LINKER_FLAGS'] = ' '.join(ldflags)\n defines['CMAKE_MODULE_LINKER_FLAGS'] = ' '.join(ldflags)\n update_cmake_sysroot_flags(defines, sysroot)\n\n macro_api_level = 10000 if platform else api_level\n\n cflags = [\n debug_prefix_flag(),\n '--target=%s' % llvm_triple,\n '-B%s' % toolchain_bin,\n '-D__ANDROID_API__=' + str(macro_api_level),\n '-ffunction-sections',\n '-fdata-sections',\n extra_flags,\n ]\n yield (arch, llvm_triple, defines, cflags)\n\n\ndef build_asan_test(toolchain):\n # We can not build asan_test using current CMake building system. Since\n # those files are not used to build AOSP, we just simply touch them so that\n # we can pass the build checks.\n for arch in ('aarch64', 'arm', 'i686'):\n asan_test_path = os.path.join(toolchain, 'test', arch, 'bin')\n check_create_path(asan_test_path)\n asan_test_bin_path = os.path.join(asan_test_path, 'asan_test')\n open(asan_test_bin_path, 'w+').close()\n\ndef build_sanitizer_map_file(san, arch, lib_dir):\n lib_file = os.path.join(lib_dir, 'libclang_rt.{}-{}-android.so'.format(san, arch))\n map_file = os.path.join(lib_dir, 'libclang_rt.{}-{}-android.map.txt'.format(san, arch))\n mapfile.create_map_file(lib_file, map_file)\n\ndef build_sanitizer_map_files(toolchain, clang_version):\n lib_dir = os.path.join(toolchain,\n clang_resource_dir(clang_version.long_version()))\n for arch in ('aarch64', 'arm', 'i686', 'x86_64'):\n build_sanitizer_map_file('asan', arch, lib_dir)\n build_sanitizer_map_file('ubsan_standalone', arch, lib_dir)\n build_sanitizer_map_file('hwasan', 'aarch64', lib_dir)\n\ndef create_hwasan_symlink(toolchain, clang_version):\n lib_dir = os.path.join(toolchain,\n clang_resource_dir(clang_version.long_version()))\n symlink_path = lib_dir + 'libclang_rt.hwasan_static-aarch64-android.a'\n utils.remove(symlink_path)\n os.symlink('libclang_rt.hwasan-aarch64-android.a', symlink_path)\n\ndef build_libcxx(toolchain, clang_version):\n for (arch, llvm_triple, libcxx_defines,\n cflags) in cross_compile_configs(toolchain): # pylint: disable=not-an-iterable\n logger().info('Building libcxx for %s', arch.value)\n libcxx_path = utils.out_path('lib', 'libcxx-' + arch.value)\n\n libcxx_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)\n libcxx_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n libcxx_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n libcxx_defines['CMAKE_BUILD_TYPE'] = 'Release'\n\n libcxx_env = dict(ORIG_ENV)\n\n libcxx_cmake_path = utils.llvm_path('libcxx')\n rm_cmake_cache(libcxx_path)\n\n invoke_cmake(\n out_path=libcxx_path,\n defines=libcxx_defines,\n env=libcxx_env,\n cmake_path=libcxx_cmake_path,\n install=False)\n # We need to install libcxx manually.\n install_subdir = clang_resource_dir(clang_version.long_version(),\n hosts.Arch.from_triple(llvm_triple))\n libcxx_install = os.path.join(toolchain, install_subdir)\n\n libcxx_libs = os.path.join(libcxx_path, 'lib')\n check_create_path(libcxx_install)\n for f in os.listdir(libcxx_libs):\n if f.startswith('libc++'):\n shutil.copy2(os.path.join(libcxx_libs, f), libcxx_install)\n\n\ndef build_crts(toolchain, clang_version, ndk_cxx=False):\n llvm_config = os.path.join(toolchain, 'bin', 'llvm-config')\n # Now build compiler-rt for each arch\n for (arch, llvm_triple, crt_defines,\n cflags) in cross_compile_configs(toolchain, platform=(not ndk_cxx)): # pylint: disable=not-an-iterable\n logger().info('Building compiler-rt for %s', arch.value)\n crt_path = utils.out_path('lib', 'clangrt-' + arch.value)\n crt_install = os.path.join(toolchain, 'lib64', 'clang',\n clang_version.long_version())\n if ndk_cxx:\n crt_path += '-ndk-cxx'\n crt_install = crt_path + '-install'\n\n crt_defines['ANDROID'] = '1'\n crt_defines['LLVM_CONFIG_PATH'] = llvm_config\n # FIXME: Disable WError build until upstream fixed the compiler-rt\n # personality routine warnings caused by r309226.\n # crt_defines['COMPILER_RT_ENABLE_WERROR'] = 'ON'\n\n # Skip implicit C++ headers and explicitly include C++ header paths.\n cflags.append('-nostdinc++')\n cflags.extend('-isystem ' + d for d in libcxx_header_dirs(ndk_cxx))\n\n cflags.append('-funwind-tables')\n\n crt_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n crt_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)\n crt_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n crt_defines['COMPILER_RT_TEST_COMPILER_CFLAGS'] = ' '.join(cflags)\n crt_defines['COMPILER_RT_TEST_TARGET_TRIPLE'] = llvm_triple\n crt_defines['COMPILER_RT_INCLUDE_TESTS'] = 'OFF'\n crt_defines['CMAKE_INSTALL_PREFIX'] = crt_install\n\n # Build libfuzzer separately.\n crt_defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'OFF'\n\n crt_defines['SANITIZER_CXX_ABI'] = 'libcxxabi'\n libs = []\n if arch == 'arm':\n libs += ['-latomic']\n if android_api(arch, platform=(not ndk_cxx)) < 21:\n libs += ['-landroid_support']\n crt_defines['SANITIZER_COMMON_LINK_LIBS'] = ' '.join(libs)\n if not ndk_cxx:\n crt_defines['COMPILER_RT_HWASAN_WITH_INTERCEPTORS'] = 'OFF'\n\n crt_defines.update(base_cmake_defines())\n\n crt_env = dict(ORIG_ENV)\n\n crt_cmake_path = utils.llvm_path('compiler-rt')\n rm_cmake_cache(crt_path)\n invoke_cmake(\n out_path=crt_path,\n defines=crt_defines,\n env=crt_env,\n cmake_path=crt_cmake_path)\n\n if ndk_cxx:\n #src_dir = os.path.join(crt_install, 'lib', 'linux')\n # 修改为lib/android\n src_dir = os.path.join(crt_install, 'lib', 'android')\n dst_dir = os.path.join(toolchain, 'runtimes_ndk_cxx')\n check_create_path(dst_dir)\n for f in os.listdir(src_dir):\n shutil.copy2(os.path.join(src_dir, f), os.path.join(dst_dir, f))\n\n\ndef build_libfuzzers(toolchain, clang_version, ndk_cxx=False):\n llvm_config = os.path.join(toolchain, 'bin', 'llvm-config')\n\n for (arch, llvm_triple, libfuzzer_defines, cflags) in cross_compile_configs( # pylint: disable=not-an-iterable\n toolchain, platform=(not ndk_cxx)):\n logger().info('Building libfuzzer for %s (ndk_cxx? %s)', arch.value, ndk_cxx)\n\n libfuzzer_path = utils.out_path('lib', 'libfuzzer-' + arch.value)\n if ndk_cxx:\n libfuzzer_path += '-ndk-cxx'\n\n libfuzzer_defines['ANDROID'] = '1'\n libfuzzer_defines['LLVM_CONFIG_PATH'] = llvm_config\n\n # Skip implicit C++ headers and explicitly include C++ header paths.\n cflags.append('-nostdinc++')\n cflags.extend('-isystem ' + d for d in libcxx_header_dirs(ndk_cxx))\n\n libfuzzer_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)\n libfuzzer_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n libfuzzer_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n\n # lib/Fuzzer/CMakeLists.txt does not call cmake_minimum_required() to\n # set a minimum version. Explicitly request a policy that'll pass\n # CMAKE_*_LINKER_FLAGS to the trycompile() step.\n libfuzzer_defines['CMAKE_POLICY_DEFAULT_CMP0056'] = 'NEW'\n\n libfuzzer_cmake_path = utils.llvm_path('compiler-rt')\n libfuzzer_env = dict(ORIG_ENV)\n rm_cmake_cache(libfuzzer_path)\n invoke_cmake(\n out_path=libfuzzer_path,\n defines=libfuzzer_defines,\n env=libfuzzer_env,\n cmake_path=libfuzzer_cmake_path,\n target='fuzzer',\n install=False)\n # We need to install libfuzzer manually.\n if arch == hosts.Arch.I386:\n sarch = 'i686'\n else:\n sarch = arch.value\n static_lib_filename = 'libclang_rt.fuzzer-' + sarch + '-android.a'\n #static_lib = os.path.join(libfuzzer_path, 'lib', 'linux', static_lib_filename)\n # libs默认是放在lib/android目录,而不是lib/linux\n static_lib = os.path.join(libfuzzer_path, 'lib', 'android', static_lib_filename)\n triple_arch: Arch = hosts.Arch.from_triple(llvm_triple)\n\n # Install the fuzzer library to the old {arch}/libFuzzer.a path for\n # backwards compatibility.\n if ndk_cxx:\n lib_subdir = os.path.join('runtimes_ndk_cxx', triple_arch.value)\n else:\n lib_subdir = clang_resource_dir(clang_version.long_version(),\n triple_arch)\n lib_dir = os.path.join(toolchain, lib_subdir)\n\n check_create_path(lib_dir)\n shutil.copy2(static_lib, os.path.join(lib_dir, 'libFuzzer.a'))\n\n # Now install under the libclang_rt.fuzzer[...] name as well.\n if ndk_cxx:\n # 1. Under runtimes_ndk_cxx\n dst_dir = os.path.join(toolchain, 'runtimes_ndk_cxx')\n check_create_path(dst_dir)\n shutil.copy2(static_lib, os.path.join(dst_dir, static_lib_filename))\n else:\n # 2. Under lib64.\n libfuzzer_install = os.path.join(toolchain, 'lib64', 'clang',\n clang_version.long_version())\n libfuzzer_install = os.path.join(libfuzzer_install, \"lib\", \"linux\")\n check_create_path(libfuzzer_install)\n shutil.copy2(static_lib, os.path.join(libfuzzer_install, static_lib_filename))\n\n # Install libfuzzer headers.\n header_src = utils.llvm_path('compiler-rt', 'lib', 'fuzzer')\n header_dst = os.path.join(toolchain, 'prebuilt_include', 'llvm', 'lib',\n 'Fuzzer')\n check_create_path(header_dst)\n for f in os.listdir(header_src):\n if f.endswith('.h') or f.endswith('.def'):\n shutil.copy2(os.path.join(header_src, f), header_dst)\n\n\ndef build_libcxxabi(toolchain, build_arch: hosts.Arch):\n # TODO: Refactor cross_compile_configs to support per-arch queries in\n # addition to being a generator.\n for (arch, llvm_triple, defines, cflags) in \\\n cross_compile_configs(toolchain, platform=True): # pylint: disable=not-an-iterable\n\n # Build only the requested arch.\n if arch != build_arch:\n continue\n\n logger().info('Building libcxxabi for %s', arch.value)\n defines['LIBCXXABI_LIBCXX_INCLUDES'] = utils.llvm_path('libcxx', 'include')\n defines['LIBCXXABI_ENABLE_SHARED'] = 'OFF'\n defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n\n out_path = utils.out_path('lib', 'libcxxabi-' + arch.value)\n if os.path.exists(out_path):\n utils.rm_tree(out_path)\n\n invoke_cmake(out_path=out_path,\n defines=defines,\n env=dict(ORIG_ENV),\n cmake_path=utils.llvm_path('libcxxabi'),\n install=False)\n return out_path\n\n\ndef build_libomp(toolchain, clang_version, ndk_cxx=False, is_shared=False):\n\n for (arch, llvm_triple, libomp_defines, cflags) in cross_compile_configs( # pylint: disable=not-an-iterable\n toolchain, platform=(not ndk_cxx)):\n\n logger().info('Building libomp for %s (ndk_cxx? %s)', arch.value, ndk_cxx)\n # Skip implicit C++ headers and explicitly include C++ header paths.\n cflags.append('-nostdinc++')\n cflags.extend('-isystem ' + d for d in libcxx_header_dirs(ndk_cxx))\n\n cflags.append('-fPIC')\n\n libomp_path = utils.out_path('lib', 'libomp-' + arch.value)\n if ndk_cxx:\n libomp_path += '-ndk-cxx'\n libomp_path += '-' + ('shared' if is_shared else 'static')\n\n libomp_defines['ANDROID'] = '1'\n libomp_defines['CMAKE_BUILD_TYPE'] = 'Release'\n libomp_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)\n libomp_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n libomp_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n libomp_defines['OPENMP_ENABLE_LIBOMPTARGET'] = 'FALSE'\n libomp_defines['OPENMP_ENABLE_OMPT_TOOLS'] = 'FALSE'\n libomp_defines['LIBOMP_ENABLE_SHARED'] = 'TRUE' if is_shared else 'FALSE'\n\n # Minimum version for OpenMP's CMake is too low for the CMP0056 policy\n # to be ON by default.\n libomp_defines['CMAKE_POLICY_DEFAULT_CMP0056'] = 'NEW'\n\n libomp_defines.update(base_cmake_defines())\n\n libomp_cmake_path = utils.llvm_path('openmp')\n libomp_env = dict(ORIG_ENV)\n rm_cmake_cache(libomp_path)\n invoke_cmake(\n out_path=libomp_path,\n defines=libomp_defines,\n env=libomp_env,\n cmake_path=libomp_cmake_path,\n install=False)\n\n # We need to install libomp manually.\n libname = 'libomp.' + ('so' if is_shared else 'a')\n src_lib = os.path.join(libomp_path, 'runtime', 'src', libname)\n triple_arch = hosts.Arch.from_triple(llvm_triple)\n if ndk_cxx:\n dst_subdir = os.path.join('runtimes_ndk_cxx', triple_arch.value)\n else:\n dst_subdir = clang_resource_dir(clang_version.long_version(),\n triple_arch)\n dst_dir = os.path.join(toolchain, dst_subdir)\n\n check_create_path(dst_dir)\n shutil.copy2(src_lib, os.path.join(dst_dir, libname))\n\n\ndef build_crts_host_i686(toolchain, clang_version):\n logger().info('Building compiler-rt for host-i686')\n\n llvm_config = os.path.join(toolchain, 'bin', 'llvm-config')\n\n crt_install = os.path.join(toolchain, 'lib64', 'clang',\n clang_version.long_version())\n crt_cmake_path = utils.llvm_path('compiler-rt')\n\n cflags, ldflags = host_gcc_toolchain_flags(hosts.build_host(), is_32_bit=True)\n\n crt_defines = base_cmake_defines()\n crt_defines['CMAKE_C_COMPILER'] = os.path.join(toolchain, 'bin',\n 'clang')\n crt_defines['CMAKE_CXX_COMPILER'] = os.path.join(toolchain, 'bin',\n 'clang++')\n\n # compiler-rt/lib/gwp_asan uses PRIu64 and similar format-specifier macros.\n # Add __STDC_FORMAT_MACROS so their definition gets included from\n # inttypes.h. This explicit flag is only needed here. 64-bit host runtimes\n # are built in stage1/stage2 and get it from the LLVM CMake configuration.\n # These are defined unconditionaly in bionic and newer glibc\n # (https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=1ef74943ce2f114c78b215af57c2ccc72ccdb0b7)\n cflags.append('-D__STDC_FORMAT_MACROS')\n\n # Due to CMake and Clang oddities, we need to explicitly set\n # CMAKE_C_COMPILER_TARGET and use march=i686 in cflags below instead of\n # relying on auto-detection from the Compiler-rt CMake files.\n \n #crt_defines['CMAKE_C_COMPILER_TARGET'] = 'i386-linux-gnu'\n crt_defines['CMAKE_C_COMPILER_TARGET'] = 'aarch64-linux-android'\n crt_defines['CMAKE_SYSROOT'] = host_sysroot()\n\n #cflags.append('--target=i386-linux-gnu')\n cflags.append('--target=aarch64-linux-android')\n #cflags.append('-march=i686')\n cflags.append('-march=armv8-a')\n\n crt_defines['LLVM_CONFIG_PATH'] = llvm_config\n crt_defines['COMPILER_RT_INCLUDE_TESTS'] = 'ON'\n crt_defines['COMPILER_RT_ENABLE_WERROR'] = 'ON'\n crt_defines['CMAKE_INSTALL_PREFIX'] = crt_install\n crt_defines['SANITIZER_CXX_ABI'] = 'libstdc++'\n\n # Set the compiler and linker flags\n crt_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)\n crt_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)\n crt_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)\n\n crt_defines['CMAKE_EXE_LINKER_FLAGS'] = ' '.join(ldflags)\n crt_defines['CMAKE_SHARED_LINKER_FLAGS'] = ' '.join(ldflags)\n crt_defines['CMAKE_MODULE_LINKER_FLAGS'] = ' '.join(ldflags)\n\n crt_env = dict(ORIG_ENV)\n\n #crt_path = utils.out_path('lib', 'clangrt-i386-host')\n crt_path = utils.out_path('lib', 'clangrt-aarch64-host')\n rm_cmake_cache(crt_path)\n\n # Also remove the \"stamps\" created for the libcxx included in libfuzzer so\n # CMake runs the configure again (after the cmake caches are deleted in the\n # line above).\n \n #utils.remove(os.path.join(crt_path, 'lib', 'fuzzer', 'libcxx_fuzzer_i386-stamps'))\n utils.remove(os.path.join(crt_path, 'lib', 'fuzzer', 'libcxx_fuzzer_aarch64-stamps'))\n\n invoke_cmake(\n out_path=crt_path,\n defines=crt_defines,\n env=crt_env,\n cmake_path=crt_cmake_path)\n\n\ndef build_llvm_for_windows(enable_assertions,\n build_name):\n win_builder = WindowsToolchainBuilder()\n if win_builder.install_dir.exists():\n shutil.rmtree(win_builder.install_dir)\n\n # Build and install libcxxabi and libcxx and use them to build Clang.\n libcxxabi_builder = LibCxxAbiBuilder()\n libcxxabi_builder.enable_assertions = enable_assertions\n libcxxabi_builder.build()\n\n libcxx_builder = LibCxxBuilder()\n libcxx_builder.enable_assertions = enable_assertions\n libcxx_builder.build()\n\n win_builder.build_name = build_name\n win_builder.svn_revision = android_version.get_svn_revision(BUILD_LLVM_NEXT)\n win_builder.build_lldb = BUILD_LLDB\n win_builder.enable_assertions = enable_assertions\n win_builder.build()\n\n return win_builder.install_dir\n\n\ndef host_sysroot():\n if hosts.build_host().is_darwin:\n return \"\"\n else:\n return utils.android_path(str(paths.GCC_ROOT / 'sysroot'))\n\n #return utils.android_path('prebuilts/gcc', hosts.build_host().os_tag,\n # 'host/x86_64-linux-glibc2.17-4.8/sysroot')\n\ndef host_gcc_toolchain_flags(host: hosts.Host, is_32_bit=False):\n cflags: List[str] = [debug_prefix_flag()]\n ldflags: List[str] = []\n\n if host.is_darwin:\n return cflags, ldflags\n\n # GCC toolchain flags for Linux and Windows\n if host.is_linux:\n gccRoot = utils.android_path(str(paths.GCC_ROOT))\n #gccRoot = utils.android_path('prebuilts/gcc', hosts.build_host().os_tag,\n # 'host/x86_64-linux-glibc2.17-4.8')\n gccTriple = 'aarch64-linux-android'\n gccVersion = '4.9.x'\n\n # gcc-toolchain is only needed for Linux\n cflags.append(f'--gcc-toolchain={gccRoot}')\n elif host.is_windows:\n gccRoot = utils.android_path('prebuilts/gcc', hosts.build_host().os_tag,\n 'host/x86_64-w64-mingw32-4.8')\n gccTriple = 'x86_64-w64-mingw32'\n gccVersion = '4.9.x'\n\n # 添加cflags\n cflags.append('-fPIC -fno-builtin-bcmp -DANDROID -D__ANDROID__')\n cflags.append('-target aarch64-linux-android')\n #/data/data/com.termux/files/home/llvm-toolchain/toolchain/llvm-project/libcxx/include\n cflags.append('-isystem /data/data/com.termux/files/home/llvm-toolchain/prebuilts/clang/host/linux-x86/clang-r377782d/include/c++/v1')\n cflags.append(f'-B{gccRoot}/{gccTriple}/bin')\n\n gccLibDir = f'{gccRoot}/lib/gcc/{gccTriple}/{gccVersion}'\n gccBuiltinDir = f'{gccRoot}/{gccTriple}/lib64'\n if is_32_bit:\n None\n #gccLibDir += '/32'\n #gccBuiltinDir = gccBuiltinDir.replace('lib64', 'lib32')\n\n ldflags.extend(('-B' + gccLibDir,\n '-L' + gccLibDir,\n '-B' + gccBuiltinDir,\n '-L' + gccBuiltinDir,\n '-fuse-ld=lld',\n ))\n\n return cflags, ldflags\n\n\nclass Stage1Builder(builders.LLVMBuilder):\n name: str = 'stage1'\n toolchain_name: str = 'prebuilt'\n install_dir: Path = paths.OUT_DIR / 'stage1-install'\n build_llvm_tools: bool = False\n build_all_targets: bool = False\n config_list: List[configs.Config] = [configs.host_config()]\n\n @property\n def llvm_targets(self) -> Set[str]:\n if self.build_all_targets:\n return set(ANDROID_TARGETS.split(';'))\n else:\n return set(BASE_TARGETS.split(';'))\n\n @property\n def llvm_projects(self) -> Set[str]:\n proj = {'clang', 'lld', 'libunwind', 'libcxxabi', 'libcxx', 'compiler-rt'}\n if self.build_llvm_tools:\n # For lldb-tblgen. It will be used to build lldb-server and\n # windows lldb.\n proj.add('lldb')\n return proj\n\n @property\n def cflags(self) -> List[str]:\n cflags = super().cflags\n cflags.append('-fPIC -D__ANDROID__ -DANDROID')\n return cflags\n\n @property\n def ldflags(self) -> List[str]:\n ldflags = super().ldflags\n ldflags.append('-ldl -lgcc -lstdc++')\n # Point CMake to the libc++.so from the prebuilts. Install an rpath\n # to prevent linking with the newly-built libc++.so\n ldflags.append(f'-Wl,-rpath,{self.toolchain.lib_dir}')\n return ldflags\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines = super().cmake_defines\n defines['CLANG_ENABLE_ARCMT'] = 'OFF'\n defines['CLANG_ENABLE_STATIC_ANALYZER'] = 'OFF'\n\n if self.build_llvm_tools:\n defines['LLVM_BUILD_TOOLS'] = 'ON'\n else:\n defines['LLVM_BUILD_TOOLS'] = 'OFF'\n\n # Make libc++.so a symlink to libc++.so.x instead of a linker script that\n # also adds -lc++abi. Statically link libc++abi to libc++ so it is not\n # necessary to pass -lc++abi explicitly. This is needed only for Linux.\n if self._config.target_os.is_linux:\n defines['LIBCXX_ENABLE_ABI_LINKER_SCRIPT'] = 'OFF'\n defines['LIBCXX_ENABLE_STATIC_ABI_LIBRARY'] = 'ON'\n\n # Do not build compiler-rt for Darwin. We don't ship host (or any\n # prebuilt) runtimes for Darwin anyway. Attempting to build these will\n # fail compilation of lib/builtins/atomic_*.c that only get built for\n # Darwin and fail compilation due to us using the bionic version of\n # stdatomic.h.\n if self._config.target_os.is_darwin:\n defines['LLVM_BUILD_EXTERNAL_COMPILER_RT'] = 'ON'\n\n # Don't build libfuzzer as part of the first stage build.\n defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'OFF'\n\n return defines\n\n @property\n def env(self) -> Dict[str, str]:\n env = super().env\n if USE_GOMA_FOR_STAGE1:\n env['USE_GOMA'] = 'true'\n return env\n\n\ndef install_lldb_deps(install_dir: Path, host: hosts.Host):\n lib_dir = install_dir / ('bin' if host.is_windows else 'lib64')\n check_create_path(lib_dir)\n\n python_prebuilt_dir: Path = paths.get_python_dir(host)\n python_dest_dir: Path = install_dir / 'python3'\n shutil.copytree(python_prebuilt_dir, python_dest_dir, symlinks=True,\n ignore=shutil.ignore_patterns('*.pyc', '__pycache__', '.git', 'Android.bp'))\n\n py_lib = paths.get_python_dynamic_lib(host).relative_to(python_prebuilt_dir)\n dest_py_lib = python_dest_dir / py_lib\n py_lib_rel = os.path.relpath(dest_py_lib, lib_dir)\n os.symlink(py_lib_rel, lib_dir / py_lib.name)\n if host.is_linux:\n shutil.copy2(paths.get_libedit_lib(host), lib_dir)\n\n\nclass Stage2Builder(builders.LLVMBuilder):\n name: str = 'stage2'\n toolchain_name: str = 'stage1'\n install_dir: Path = paths.OUT_DIR / 'stage2-install'\n config_list: List[configs.Config] = [configs.host_config()]\n remove_install_dir: bool = True\n build_lldb: bool = True\n debug_build: bool = False\n build_instrumented: bool = False\n profdata_file: Optional[Path] = None\n lto: bool = True\n \n\n @property\n def llvm_targets(self) -> Set[str]:\n return set(ANDROID_TARGETS.split(';'))\n\n @property\n def llvm_projects(self) -> Set[str]:\n proj = {'clang', 'lld', 'libunwind', 'libcxxabi', 'libcxx', 'compiler-rt', 'compiler-rt', 'clang-tools-extra', 'openmp', 'polly'} \n if self.build_lldb:\n proj.add('lldb')\n return proj\n\n @property\n def env(self) -> Dict[str, str]:\n env = super().env\n # Point CMake to the libc++ from stage1. It is possible that once built,\n # the newly-built libc++ may override this because of the rpath pointing to\n # $ORIGIN/../lib64. That'd be fine because both libraries are built from\n # the same sources.\n env['LD_LIBRARY_PATH'] = str(self.toolchain.lib_dir)\n return env\n\n @property\n def ldflags(self) -> List[str]:\n ldflags = super().ldflags\n ldflags.append('-ldl -lgcc -lstdc++ -lc++_static')\n if self.build_instrumented:\n # Building libcxx, libcxxabi with instrumentation causes linker errors\n # because these are built with -nodefaultlibs and prevent libc symbols\n # needed by libclang_rt.profile from being resolved. Manually adding\n # the libclang_rt.profile to linker flags fixes the issue.\n resource_dir = self.toolchain.get_resource_dir()\n ldflags.append(str(resource_dir / 'libclang_rt.profile-x86_64.a'))\n return ldflags\n\n @property\n def cflags(self) -> List[str]:\n cflags = super().cflags\n cflags.append('-fPIC -frtti -fexceptions -fno-builtin-bcmp -DANDROID -D__ANDROID__')\n cflags.append('-target aarch64-linux-android')\n # /data/data/com.termux/files/home/llvm-toolchain/toolchain/llvm-project/libcxx/include\n cflags.append('-isystem ' + str(ANDROID_DIR / 'toolchain/llvm-project/libcxx/include'))\n if self.profdata_file:\n cflags.append('-Wno-profile-instr-out-of-date')\n cflags.append('-Wno-profile-instr-unprofiled')\n return cflags\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines = super().cmake_defines\n # static building\n # defines['LLVM_BUILD_STATIC'] = 'TRUE'\n defines['LLVM_ENABLE_LIBCXX'] = 'ON'\n defines['SANITIZER_ALLOW_CXXABI'] = 'OFF'\n defines['OPENMP_ENABLE_OMPT_TOOLS'] = 'FALSE'\n defines['LIBOMP_ENABLE_SHARED'] = 'FALSE'\n\n if (self.lto and\n not self._config.target_os.is_darwin and\n not self.build_instrumented and\n not self.debug_build):\n defines['LLVM_ENABLE_LTO'] = 'Thin'\n\n # Build libFuzzer here to be exported for the host fuzzer builds. libFuzzer\n # is not currently supported on Darwin.\n if self._config.target_os.is_darwin:\n defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'OFF'\n else:\n defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'ON'\n\n if self.debug_build:\n defines['CMAKE_BUILD_TYPE'] = 'Debug'\n\n if self.build_instrumented:\n defines['LLVM_BUILD_INSTRUMENTED'] = 'ON'\n\n # llvm-profdata is only needed to finish CMake configuration\n # (tools/clang/utils/perf-training/CMakeLists.txt) and not needed for\n # build\n llvm_profdata = self.toolchain.path / 'bin' / 'llvm-profdata'\n defines['LLVM_PROFDATA'] = str(llvm_profdata)\n elif self.profdata_file:\n defines['LLVM_PROFDATA_FILE'] = str(self.profdata_file)\n\n # Make libc++.so a symlink to libc++.so.x instead of a linker script that\n # also adds -lc++abi. Statically link libc++abi to libc++ so it is not\n # necessary to pass -lc++abi explicitly. This is needed only for Linux.\n if self._config.target_os.is_linux:\n defines['LIBCXX_ENABLE_STATIC_ABI_LIBRARY'] = 'ON'\n defines['LIBCXX_ENABLE_ABI_LINKER_SCRIPT'] = 'OFF'\n\n # Do not build compiler-rt for Darwin. We don't ship host (or any\n # prebuilt) runtimes for Darwin anyway. Attempting to build these will\n # fail compilation of lib/builtins/atomic_*.c that only get built for\n # Darwin and fail compilation due to us using the bionic version of\n # stdatomic.h.\n if self._config.target_os.is_darwin:\n defines['LLVM_BUILD_EXTERNAL_COMPILER_RT'] = 'ON'\n\n return defines\n\n\nclass LldbServerBuilder(builders.LLVMRuntimeBuilder):\n name: str = 'lldb-server'\n src_dir: Path = paths.LLVM_PATH / 'llvm'\n config_list: List[configs.Config] = configs.android_configs(platform=False, static=True)\n ninja_target: str = 'lldb-server'\n\n @property\n def install_dir(self) -> Path:\n return self.toolchain.path / 'runtimes_ndk_cxx' / self._config.target_arch.value\n\n @property\n def cflags(self) -> List[str]:\n cflags: List[str] = super().cflags\n # The build system will add '-stdlib=libc++' automatically. Since we\n # have -nostdinc++ here, -stdlib is useless. Adds a flag to avoid the\n # warnings.\n cflags.append('-Wno-unused-command-line-argument')\n return cflags\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines = super().cmake_defines\n # lldb depends on support libraries.\n defines['LLVM_ENABLE_PROJECTS'] = 'clang;lldb'\n defines['LLVM_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'llvm-tblgen')\n defines['CLANG_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'clang-tblgen')\n defines['LLDB_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'lldb-tblgen')\n return defines\n\n def install(self) -> None:\n src_path = self.output_dir / 'bin' / 'lldb-server'\n install_dir = self.install_dir\n install_dir.mkdir(parents=True, exist_ok=True)\n shutil.copy2(src_path, install_dir)\n\n\nclass LibCxxAbiBuilder(builders.LLVMRuntimeBuilder):\n name = 'libcxxabi'\n src_dir: Path = paths.LLVM_PATH / 'libcxxabi'\n config_list: List[configs.Config] = [configs.WindowsConfig()]\n remove_cmake_cache: bool = True\n\n @property\n def install_dir(self):\n return paths.OUT_DIR / 'windows-x86-64-install'\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines: Dict[str, str] = super().cmake_defines\n defines['LIBCXXABI_ENABLE_NEW_DELETE_DEFINITIONS'] = 'OFF'\n defines['LIBCXXABI_LIBCXX_INCLUDES'] = str(paths.LLVM_PATH /'libcxx' / 'include')\n\n # Build only the static library.\n defines['LIBCXXABI_ENABLE_SHARED'] = 'OFF'\n\n if self.enable_assertions:\n defines['LIBCXXABI_ENABLE_ASSERTIONS'] = 'ON'\n\n return defines\n\n @property\n def cflags(self) -> List[str]:\n cflags: List[str] = super().cflags\n # Disable libcxx visibility annotations and enable WIN32 threads. These\n # are needed because the libcxxabi build happens before libcxx and uses\n # headers directly from the sources.\n cflags.append('-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS')\n cflags.append('-D_LIBCPP_HAS_THREAD_API_WIN32')\n return cflags\n\n\nclass LibCxxBuilder(builders.LLVMRuntimeBuilder):\n name = 'libcxx'\n src_dir: Path = paths.LLVM_PATH / 'libcxx'\n config_list: List[configs.Config] = [configs.WindowsConfig()]\n remove_cmake_cache: bool = True\n\n @property\n def install_dir(self):\n return paths.OUT_DIR / 'windows-x86-64-install'\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines: Dict[str, str] = super().cmake_defines\n defines['LIBCXX_ENABLE_STATIC_ABI_LIBRARY'] = 'ON'\n defines['LIBCXX_CXX_ABI'] = 'libcxxabi'\n defines['LIBCXX_HAS_WIN32_THREAD_API'] = 'ON'\n\n # Use cxxabi header from the source directory since it gets installed\n # into install_dir only during libcxx's install step. But use the\n # library from install_dir.\n defines['LIBCXX_CXX_ABI_INCLUDE_PATHS'] = str(paths.LLVM_PATH / 'libcxxabi' / 'include')\n defines['LIBCXX_CXX_ABI_LIBRARY_PATH'] = str(BuilderRegistry.get('libcxxabi').install_dir / 'lib64')\n\n # Build only the static library.\n defines['LIBCXX_ENABLE_SHARED'] = 'OFF'\n\n if self.enable_assertions:\n defines['LIBCXX_ENABLE_ASSERTIONS'] = 'ON'\n\n return defines\n\n @property\n def cflags(self) -> List[str]:\n cflags: List[str] = super().cflags\n # Disable libcxxabi visibility annotations since we're only building it\n # statically.\n cflags.append('-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS')\n return cflags\n\n\nclass WindowsToolchainBuilder(builders.LLVMBuilder):\n name: str = 'windows-x86-64'\n toolchain_name: str = 'stage1'\n config_list: List[configs.Config] = [configs.WindowsConfig()]\n build_lldb: bool = True\n\n @property\n def install_dir(self) -> Path:\n return paths.OUT_DIR / 'windows-x86-64-install'\n\n @property\n def llvm_targets(self) -> Set[str]:\n return set(ANDROID_TARGETS.split(';'))\n\n @property\n def llvm_projects(self) -> Set[str]:\n proj = {'clang', 'clang-tools-extra', 'lld'}\n if self.build_lldb:\n proj.add('lldb')\n return proj\n\n @property\n def cmake_defines(self) -> Dict[str, str]:\n defines = super().cmake_defines\n # Don't build compiler-rt, libcxx etc. for Windows\n defines['LLVM_BUILD_RUNTIME'] = 'OFF'\n # Build clang-tidy/clang-format for Windows.\n defines['LLVM_TOOL_CLANG_TOOLS_EXTRA_BUILD'] = 'ON'\n defines['LLVM_TOOL_OPENMP_BUILD'] = 'OFF'\n # Don't build tests for Windows.\n defines['LLVM_INCLUDE_TESTS'] = 'OFF'\n\n defines['LLVM_CONFIG_PATH'] = str(self.toolchain.build_path / 'bin' / 'llvm-config')\n defines['LLVM_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'llvm-tblgen')\n defines['CLANG_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'clang-tblgen')\n if self.build_lldb:\n defines['LLDB_TABLEGEN'] = str(self.toolchain.build_path / 'bin' / 'lldb-tblgen')\n return defines\n\n @property\n def ldflags(self) -> List[str]:\n ldflags = super().ldflags\n ldflags.append('-Wl,--dynamicbase')\n ldflags.append('-Wl,--nxcompat')\n # Use static-libgcc to avoid runtime dependence on libgcc_eh.\n ldflags.append('-static-libgcc')\n # pthread is needed by libgcc_eh.\n ldflags.append('-pthread')\n # Add path to libc++, libc++abi.\n libcxx_lib = BuilderRegistry.get('libcxx').install_dir / 'lib64'\n ldflags.append(f'-L{libcxx_lib}')\n ldflags.append('-Wl,--high-entropy-va')\n ldflags.append('-Wl,--Xlink=-Brepro')\n ldflags.append(f'-L{paths.WIN_ZLIB_LIB_PATH}')\n return ldflags\n\n @property\n def cflags(self) -> List[str]:\n cflags = super().cflags\n cflags.append('-DMS_WIN64')\n cflags.append(f'-I{paths.WIN_ZLIB_INCLUDE_PATH}')\n return cflags\n\n @property\n def cxxflags(self) -> List[str]:\n cxxflags = super().cxxflags\n\n # Use -fuse-cxa-atexit to allow static TLS destructors. This is needed for\n # clang-tools-extra/clangd/Context.cpp\n cxxflags.append('-fuse-cxa-atexit')\n\n # Explicitly add the path to libc++ headers. We don't need to configure\n # options like visibility annotations, win32 threads etc. because the\n # __generated_config header in the patch captures all the options used when\n # building libc++.\n cxx_headers = BuilderRegistry.get('libcxx').install_dir / 'include' / 'c++' / 'v1'\n cxxflags.append(f'-I{cxx_headers}')\n\n return cxxflags\n\n\ndef build_runtimes(toolchain, args=None):\n if not BuilderRegistry.should_build('sysroot'):\n logger().info('Skip libcxxabi and other sysroot libraries')\n else:\n create_sysroots()\n version = extract_clang_version(toolchain)\n if not BuilderRegistry.should_build('compiler-rt'):\n logger().info('Skip compiler-rt')\n else:\n #build_crts(toolchain, version)\n #build_crts(toolchain, version, ndk_cxx=True)\n # 32-bit host crts are not needed for Darwin\n if hosts.build_host().is_linux:\n build_crts_host_i686(toolchain, version)\n if not BuilderRegistry.should_build('libfuzzers'):\n logger().info('Skip libfuzzers')\n else:\n build_libfuzzers(toolchain, version)\n build_libfuzzers(toolchain, version, ndk_cxx=True)\n if not BuilderRegistry.should_build('libomp'):\n logger().info('Skip libomp')\n else:\n build_libomp(toolchain, version)\n build_libomp(toolchain, version, ndk_cxx=True)\n build_libomp(toolchain, version, ndk_cxx=True, is_shared=True)\n if BUILD_LLDB:\n LldbServerBuilder().build()\n # Bug: http://b/64037266. `strtod_l` is missing in NDK r15. This will break\n # libcxx build.\n # build_libcxx(toolchain, version)\n if not BuilderRegistry.should_build('asan'):\n logger().info('Skip asan test, map, symlink')\n else:\n build_asan_test(toolchain)\n build_sanitizer_map_files(toolchain, version)\n create_hwasan_symlink(toolchain, version)\n\ndef install_wrappers(llvm_install_path):\n wrapper_path = utils.out_path('llvm_android_wrapper')\n wrapper_build_script = utils.android_path('external', 'toolchain-utils',\n 'compiler_wrapper', 'build.py')\n # Note: The build script automatically determines the architecture\n # based on the host.\n go_env = dict(os.environ)\n go_env['PATH'] = go_bin_dir() + ':' + go_env['PATH']\n utils.check_call([sys.executable, wrapper_build_script,\n '--config=android',\n '--use_ccache=false',\n '--use_llvm_next=' + str(BUILD_LLVM_NEXT).lower(),\n '--output_file=' + wrapper_path], env=go_env)\n\n bisect_path = utils.android_path('toolchain', 'llvm_android',\n 'bisect_driver.py')\n bin_path = os.path.join(llvm_install_path, 'bin')\n clang_path = os.path.join(bin_path, 'clang')\n clangxx_path = os.path.join(bin_path, 'clang++')\n clang_tidy_path = os.path.join(bin_path, 'clang-tidy')\n\n # Rename clang and clang++ to clang.real and clang++.real.\n # clang and clang-tidy may already be moved by this script if we use a\n # prebuilt clang. So we only move them if clang.real and clang-tidy.real\n # doesn't exist.\n if not os.path.exists(clang_path + '.real'):\n shutil.move(clang_path, clang_path + '.real')\n if not os.path.exists(clang_tidy_path + '.real'):\n shutil.move(clang_tidy_path, clang_tidy_path + '.real')\n utils.remove(clang_path)\n utils.remove(clangxx_path)\n utils.remove(clang_tidy_path)\n utils.remove(clangxx_path + '.real')\n os.symlink('clang.real', clangxx_path + '.real')\n\n shutil.copy2(wrapper_path, clang_path)\n shutil.copy2(wrapper_path, clangxx_path)\n shutil.copy2(wrapper_path, clang_tidy_path)\n install_file(bisect_path, bin_path)\n\n\n# Normalize host libraries (libLLVM, libclang, libc++, libc++abi) so that there\n# is just one library, whose SONAME entry matches the actual name.\ndef normalize_llvm_host_libs(install_dir, host: hosts.Host, version):\n if host.is_linux:\n libs = {'libLLVM': 'libLLVM-{version}git.so',\n 'libclang': 'libclang.so.{version}git',\n 'libclang_cxx': 'libclang_cxx.so.{version}git',\n 'libc++': 'libc++.so.{version}',\n 'libc++abi': 'libc++abi.so.{version}'\n }\n else:\n libs = {'libc++': 'libc++.{version}.dylib',\n 'libc++abi': 'libc++abi.{version}.dylib'\n }\n\n def getVersions(libname):\n if not libname.startswith('libc++'):\n return version.short_version(), version.major\n else:\n return '1.0', '1'\n\n libdir = os.path.join(install_dir, 'lib64')\n for libname, libformat in libs.items():\n short_version, major = getVersions(libname)\n\n soname_lib = os.path.join(libdir, libformat.format(version=major))\n if libname.startswith('libclang'):\n real_lib = soname_lib[:-3]\n else:\n real_lib = os.path.join(libdir, libformat.format(version=short_version))\n\n if libname not in ('libLLVM',):\n # Rename the library to match its SONAME\n if not os.path.isfile(real_lib):\n raise RuntimeError(real_lib + ' must be a regular file')\n if not os.path.islink(soname_lib):\n raise RuntimeError(soname_lib + ' must be a symlink')\n\n shutil.move(real_lib, soname_lib)\n\n # Retain only soname_lib and delete other files for this library. We\n # still need libc++.so or libc++.dylib symlinks for a subsequent stage1\n # build using these prebuilts (where CMake tries to find C++ atomics\n # support) to succeed.\n libcxx_name = 'libc++.so' if host.is_linux else 'libc++.dylib'\n all_libs = [lib for lib in os.listdir(libdir) if\n lib != libcxx_name and\n not lib.endswith('.a') and # skip static host libraries\n (lib.startswith(libname + '.') or # so libc++abi is ignored\n lib.startswith(libname + '-'))]\n\n for lib in all_libs:\n lib = os.path.join(libdir, lib)\n if lib != soname_lib:\n remove(lib)\n\n\ndef install_license_files(install_dir):\n projects = (\n 'llvm',\n 'compiler-rt',\n 'libcxx',\n 'libcxxabi',\n 'openmp',\n 'clang',\n 'clang-tools-extra',\n 'lld',\n )\n\n # Get generic MODULE_LICENSE_* files from our android subdirectory.\n llvm_android_path = utils.android_path('toolchain', 'llvm_android')\n license_pattern = os.path.join(llvm_android_path, 'MODULE_LICENSE_*')\n for license_file in glob.glob(license_pattern):\n install_file(license_file, install_dir)\n\n # Fetch all the LICENSE.* files under our projects and append them into a\n # single NOTICE file for the resulting prebuilts.\n notices = []\n for project in projects:\n license_pattern = utils.llvm_path(project, 'LICENSE.*')\n for license_file in glob.glob(license_pattern):\n with open(license_file) as notice_file:\n notices.append(notice_file.read())\n with open(os.path.join(install_dir, 'NOTICE'), 'w') as notice_file:\n notice_file.write('\\n'.join(notices))\n\n\ndef install_winpthreads(bin_dir, lib_dir):\n \"\"\"Installs the winpthreads runtime to the Windows bin and lib directory.\"\"\"\n lib_name = 'libwinpthread-1.dll'\n mingw_dir = utils.android_path(\n 'prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8',\n 'x86_64-w64-mingw32')\n lib_path = os.path.join(mingw_dir, 'bin', lib_name)\n\n lib_install = os.path.join(lib_dir, lib_name)\n install_file(lib_path, lib_install)\n\n bin_install = os.path.join(bin_dir, lib_name)\n install_file(lib_path, bin_install)\n\n\ndef remove_static_libraries(static_lib_dir, necessary_libs=None):\n if not necessary_libs:\n necessary_libs = {}\n if os.path.isdir(static_lib_dir):\n lib_files = os.listdir(static_lib_dir)\n for lib_file in lib_files:\n if lib_file.endswith('.a') and lib_file not in necessary_libs:\n static_library = os.path.join(static_lib_dir, lib_file)\n remove(static_library)\n\n\ndef get_package_install_path(host: hosts.Host, package_name):\n return utils.out_path('install', host.os_tag, package_name)\n\n\ndef package_toolchain(build_dir, build_name, host: hosts.Host, dist_dir, strip=True, create_tar=True):\n package_name = 'clang-' + build_name\n version = extract_clang_version(build_dir)\n\n install_dir = get_package_install_path(host, package_name)\n install_host_dir = os.path.realpath(os.path.join(install_dir, '../'))\n\n # Remove any previously installed toolchain so it doesn't pollute the\n # build.\n if os.path.exists(install_host_dir):\n shutil.rmtree(install_host_dir)\n\n # First copy over the entire set of output objects.\n shutil.copytree(build_dir, install_dir, symlinks=True)\n\n ext = '.exe' if host.is_windows else ''\n shlib_ext = '.dll' if host.is_windows else '.so' if host.is_linux else '.dylib'\n\n # Next, we remove unnecessary binaries.\n necessary_bin_files = {\n 'clang' + ext,\n 'clang++' + ext,\n 'clang-' + version.major_version() + ext,\n 'clang-check' + ext,\n 'clang-cl' + ext,\n 'clang-format' + ext,\n 'clang-tidy' + ext,\n 'dsymutil' + ext,\n 'git-clang-format', # No extension here\n 'ld.lld' + ext,\n 'ld64.lld' + ext,\n 'lld' + ext,\n 'lld-link' + ext,\n 'llvm-addr2line' + ext,\n 'llvm-ar' + ext,\n 'llvm-as' + ext,\n 'llvm-cfi-verify' + ext,\n 'llvm-config' + ext,\n 'llvm-cov' + ext,\n 'llvm-dis' + ext,\n 'llvm-lib' + ext,\n 'llvm-link' + ext,\n 'llvm-modextract' + ext,\n 'llvm-nm' + ext,\n 'llvm-objcopy' + ext,\n 'llvm-objdump' + ext,\n 'llvm-profdata' + ext,\n 'llvm-ranlib' + ext,\n 'llvm-rc' + ext,\n 'llvm-readelf' + ext,\n 'llvm-readobj' + ext,\n 'llvm-size' + ext,\n 'llvm-strings' + ext,\n 'llvm-strip' + ext,\n 'llvm-symbolizer' + ext,\n 'sancov' + ext,\n 'sanstats' + ext,\n 'scan-build' + ext,\n 'scan-view' + ext,\n }\n\n if BUILD_LLDB:\n necessary_bin_files.update({\n 'lldb-argdumper' + ext,\n 'lldb' + ext,\n })\n\n if host.is_windows:\n windows_blacklist_bin_files = {\n 'clang-' + version.major_version() + ext,\n 'scan-build' + ext,\n 'scan-view' + ext,\n }\n necessary_bin_files -= windows_blacklist_bin_files\n\n if BUILD_LLDB:\n install_lldb_deps(Path(install_dir), host)\n if host.is_windows:\n windows_additional_bin_files = {\n 'liblldb' + shlib_ext,\n 'python38' + shlib_ext\n }\n necessary_bin_files |= windows_additional_bin_files\n\n # scripts that should not be stripped\n script_bins = {\n 'git-clang-format',\n 'scan-build',\n 'scan-view',\n }\n\n bin_dir = os.path.join(install_dir, 'bin')\n lib_dir = os.path.join(install_dir, 'lib64')\n\n for bin_filename in os.listdir(bin_dir):\n binary = os.path.join(bin_dir, bin_filename)\n if os.path.isfile(binary):\n if bin_filename not in necessary_bin_files:\n remove(binary)\n elif strip and bin_filename not in script_bins:\n utils.check_call(['strip', binary])\n\n # FIXME: check that all libs under lib64/clang// are created.\n for necessary_bin_file in necessary_bin_files:\n if not os.path.isfile(os.path.join(bin_dir, necessary_bin_file)):\n raise RuntimeError('Did not find %s in %s' % (necessary_bin_file, bin_dir))\n\n necessary_lib_files = {\n 'libc++.a',\n 'libc++abi.a',\n }\n\n if host.is_windows:\n necessary_lib_files |= {\n 'LLVMgold' + shlib_ext,\n 'libwinpthread-1' + shlib_ext,\n }\n # For Windows, add other relevant libraries.\n install_winpthreads(bin_dir, lib_dir)\n\n # Remove unnecessary static libraries.\n remove_static_libraries(lib_dir, necessary_lib_files)\n\n if not host.is_windows:\n install_wrappers(install_dir)\n normalize_llvm_host_libs(install_dir, host, version)\n\n # Check necessary lib files exist.\n for necessary_lib_file in necessary_lib_files:\n if not os.path.isfile(os.path.join(lib_dir, necessary_lib_file)):\n raise RuntimeError('Did not find %s in %s' % (necessary_lib_file, lib_dir))\n\n # Next, we copy over stdatomic.h and bits/stdatomic.h from bionic.\n libc_include_path = utils.android_path('bionic', 'libc', 'include')\n resdir_top = os.path.join(lib_dir, 'clang')\n header_path = os.path.join(resdir_top, version.long_version(), 'include')\n\n stdatomic_path = utils.android_path(libc_include_path, 'stdatomic.h')\n install_file(stdatomic_path, header_path)\n\n bits_install_path = os.path.join(header_path, 'bits')\n if not os.path.isdir(bits_install_path):\n os.mkdir(bits_install_path)\n bits_stdatomic_path = utils.android_path(libc_include_path, 'bits', 'stdatomic.h')\n install_file(bits_stdatomic_path, bits_install_path)\n\n\n # Install license files as NOTICE in the toolchain install dir.\n install_license_files(install_dir)\n\n # Add an AndroidVersion.txt file.\n version_file_path = os.path.join(install_dir, 'AndroidVersion.txt')\n with open(version_file_path, 'w') as version_file:\n version_file.write('{}\\n'.format(version.long_version()))\n svn_revision = android_version.get_svn_revision(BUILD_LLVM_NEXT)\n version_file.write('based on {}\\n'.format(svn_revision))\n\n # Create RBE input files.\n if host.is_linux:\n with open(os.path.join(install_dir, 'bin', 'remote_toolchain_inputs'), 'w') as inputs_file:\n dependencies = ('clang\\n'\n 'clang++\\n'\n 'clang.real\\n'\n 'clang++.real\\n'\n '../lib64/libc++.so.1\\n'\n 'lld\\n'\n 'ld64.lld\\n'\n 'ld.lld\\n'\n )\n blacklist_dir = os.path.join('../', 'lib64', 'clang', version.long_version(), 'share\\n')\n libs_dir = os.path.join('../', 'lib64', 'clang', version.long_version(), 'lib', 'linux\\n')\n dependencies += (blacklist_dir + libs_dir)\n inputs_file.write(dependencies)\n\n # Package up the resulting trimmed install/ directory.\n if create_tar:\n tarball_name = package_name + '-' + host.os_tag\n package_path = os.path.join(dist_dir, tarball_name) + '.tar.bz2'\n logger().info('Packaging %s', package_path)\n args = ['tar', '-cjC', install_host_dir, '-f', package_path, package_name]\n utils.check_call(args)\n\n\ndef parse_args():\n known_components = ('linux', 'windows', 'lldb')\n known_components_str = ', '.join(known_components)\n\n # Simple argparse.Action to allow comma-separated values (e.g.\n # --option=val1,val2)\n class CommaSeparatedListAction(argparse.Action):\n def __call__(self, parser, namespace, values, option_string):\n for value in values.split(','):\n if value not in known_components:\n error = '\\'{}\\' invalid. Choose from {}'.format(\n value, known_platforms)\n raise argparse.ArgumentError(self, error)\n setattr(namespace, self.dest, values.split(','))\n\n\n # Parses and returns command line arguments.\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '-v',\n '--verbose',\n action='count',\n default=0,\n help='Increase log level. Defaults to logging.INFO.')\n parser.add_argument(\n '--build-name', default='dev', help='Release name for the package.')\n\n parser.add_argument(\n '--enable-assertions',\n action='store_true',\n default=False,\n help='Enable assertions (only affects stage2)')\n\n parser.add_argument(\n '--no-lto',\n action='store_true',\n default=False,\n help='Disable LTO to speed up build (only affects stage2)')\n\n parser.add_argument(\n '--debug',\n action='store_true',\n default=False,\n help='Build debuggable Clang and LLVM tools (only affects stage2)')\n\n parser.add_argument(\n '--build-instrumented',\n action='store_true',\n default=False,\n help='Build LLVM tools with PGO instrumentation')\n\n # Options to skip build or packaging (can't skip both, or the script does\n # nothing).\n build_package_group = parser.add_mutually_exclusive_group()\n build_package_group.add_argument(\n '--skip-build',\n '-sb',\n action='store_true',\n default=False,\n help='Skip the build, and only do the packaging step')\n build_package_group.add_argument(\n '--skip-package',\n '-sp',\n action='store_true',\n default=False,\n help='Skip the packaging, and only do the build step')\n\n parser.add_argument(\n '--no-strip',\n action='store_true',\n default=False,\n help='Don\\'t strip binaries/libraries')\n\n build_group = parser.add_mutually_exclusive_group()\n build_group.add_argument(\n '--build',\n nargs='+',\n help='A list of builders to build. All builders not listed will be skipped.')\n build_group.add_argument(\n '--skip',\n nargs='+',\n help='A list of builders to skip. All builders not listed will be built.')\n\n # skip_runtimes is set to skip recompilation of libraries\n parser.add_argument(\n '--skip-runtimes',\n action='store_true',\n default=False,\n help='Skip the runtime libraries')\n\n parser.add_argument(\n '--no-build',\n action=CommaSeparatedListAction,\n default=list(),\n help='Don\\'t build toolchain components or platforms. Choices: ' + \\\n known_components_str)\n\n parser.add_argument(\n '--check-pgo-profile',\n action='store_true',\n default=False,\n help='Fail if expected PGO profile doesn\\'t exist')\n\n parser.add_argument(\n '--build-llvm-next',\n action='store_true',\n default=False,\n help='Build next LLVM revision (android_version.py:svn_revision_next)')\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n if args.skip_build:\n # Skips all builds\n BuilderRegistry.add_filter(lambda name: False)\n elif args.skip:\n BuilderRegistry.add_skips(args.skip)\n elif args.build:\n BuilderRegistry.add_builds(args.build)\n do_runtimes = not args.skip_runtimes\n do_package = not args.skip_package\n do_strip = not args.no_strip\n do_strip_host_package = do_strip and not args.debug\n\n # TODO (Pirama): Avoid using global statement\n global BUILD_LLDB, BUILD_LLVM_NEXT\n BUILD_LLDB = 'lldb' not in args.no_build\n BUILD_LLVM_NEXT = args.build_llvm_next\n\n need_host = hosts.build_host().is_darwin or ('linux' not in args.no_build)\n need_windows = hosts.build_host().is_linux and ('windows' not in args.no_build)\n\n log_levels = [logging.INFO, logging.DEBUG]\n verbosity = min(args.verbose, len(log_levels) - 1)\n log_level = log_levels[verbosity]\n logging.basicConfig(level=log_level)\n\n logger().info('do_build=%r do_stage1=%r do_stage2=%r do_runtimes=%r do_package=%r need_windows=%r' %\n (not args.skip_build, BuilderRegistry.should_build('stage1'), BuilderRegistry.should_build('stage2'),\n do_runtimes, do_package, need_windows))\n\n # Clone sources to be built and apply patches.\n source_manager.setup_sources(source_dir=utils.llvm_path(),\n build_llvm_next=args.build_llvm_next)\n\n # Build the stage1 Clang for the build host\n instrumented = hosts.build_host().is_linux and args.build_instrumented\n\n # Windows libs are built with stage1 toolchain. llvm-config is required.\n stage1_build_llvm_tools = instrumented or \\\n need_windows or \\\n args.debug\n \n stage1 = Stage1Builder()\n stage1.build_name = args.build_name\n stage1.svn_revision = android_version.get_svn_revision(BUILD_LLVM_NEXT)\n stage1.build_llvm_tools = stage1_build_llvm_tools\n stage1.build_all_targets = args.debug or instrumented\n stage1.build()\n stage1_install = str(stage1.install_dir)\n \n if need_host:\n profdata_filename = pgo_profdata_filename()\n profdata = pgo_profdata_file(profdata_filename)\n # Do not use PGO profiles if profdata file doesn't exist unless failure\n # is explicitly requested via --check-pgo-profile.\n if profdata is None and args.check_pgo_profile:\n raise RuntimeError('Profdata file does not exist for ' +\n profdata_filename)\n\n stage2 = Stage2Builder()\n stage2.build_name = args.build_name\n stage2.svn_revision = android_version.get_svn_revision(BUILD_LLVM_NEXT)\n stage2.build_lldb = BUILD_LLDB\n stage2.debug_build = args.debug\n stage2.enable_assertions = args.enable_assertions\n stage2.lto = not args.no_lto\n stage2.build_instrumented = instrumented\n stage2.profdata_file = Path(profdata) if profdata else None\n stage2.build()\n stage2_install = str(stage2.install_dir)\n\n if hosts.build_host().is_linux and do_runtimes:\n runtimes_toolchain = stage2_install\n if args.debug or instrumented:\n runtimes_toolchain = stage1_install\n build_runtimes(runtimes_toolchain, args)\n\n if need_windows:\n windows64_install = build_llvm_for_windows(\n enable_assertions=args.enable_assertions,\n build_name=args.build_name)\n\n dist_dir = ORIG_ENV.get('DIST_DIR', utils.out_path())\n if do_package and need_host:\n package_toolchain(\n stage2_install,\n args.build_name,\n hosts.build_host(),\n dist_dir,\n strip=do_strip_host_package)\n\n if do_package and need_windows:\n package_toolchain(\n windows64_install,\n args.build_name,\n hosts.Host.Windows,\n dist_dir,\n strip=do_strip)\n\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"llvm_android/do_build.py","file_name":"do_build.py","file_ext":"py","file_size_in_byte":73733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"322630033","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport webapp2\nfrom icalendar import Calendar\nfrom google.appengine.api.urlfetch import fetch\n\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n user = self.request.get('user')\n if len(user) == 0:\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.write('Username not supplied')\n return\n\n content = self.combine_calendars(user)\n self.response.headers['Content-Type'] = 'text/calendar;charset=utf-8'\n self.response.write(content)\n\n def combine_calendars(self, user):\n cal = Calendar()\n cal.add('prodid', '-//My calendar product//mxm.dk//')\n cal.add('version', '2.0')\n\n url = 'http://ws.audioscrobbler.com/2.0/user/%s/pastevents.ical' % user\n past = fetch(url)\n pastcal = Calendar.from_ical(past.content)\n\n url = 'http://ws.audioscrobbler.com/2.0/user/%s/events.ical' % user\n future = fetch(url)\n futcal = Calendar.from_ical(future.content)\n\n for e in pastcal.walk(name='VEVENT'):\n cal.add_component(e)\n\n for e in futcal.walk(name='VEVENT'):\n cal.add_component(e)\n\n return cal.to_ical()\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler)\n ], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"275081972","text":"# Copyright (C) 2020 THL A29 Limited, a Tencent company.\n# All rights reserved.\n# Licensed under the BSD 3-Clause License (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n# https://opensource.org/licenses/BSD-3-Clause\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# See the AUTHORS file for names of contributors.\nimport torch\nimport transformers\nimport turbo_transformers\nimport enum\nimport time\nimport sys\n\n\ndef serial_bert_inference(torch_model, input_list):\n res_list = []\n for input_seq in input_list:\n res, _ = torch_model(input_seq)\n res_list.append(res)\n\n for i in range(len(res_list)):\n if i == 0:\n concat_res = res_list[i]\n else:\n concat_res = torch.cat((concat_res, res_list[i]), 1)\n return concat_res\n\n\ndef batch_bert_inference(turbo_model, input_list, query_seq_len_list):\n res, _ = turbo_model(input_list, query_seq_len_list)\n return res\n\n\ndef test_smart_batch(use_cuda: bool):\n test_device = torch.device('cuda:0') if use_cuda else \\\n torch.device('cpu:0')\n cfg = transformers.BertConfig(attention_probs_dropout_prob=0.0,\n hidden_dropout_prob=0.0)\n torch_model = transformers.BertModel(cfg)\n\n # model_id = \"bert-base-uncased\"\n # torch_model = transformers.BertModel.from_pretrained(model_id)\n torch_model.eval()\n torch_model.to(test_device)\n torch.set_grad_enabled(False)\n\n cfg = torch_model.config\n # use 4 threads for computing\n if not use_cuda:\n turbo_transformers.set_num_threads(4)\n\n # Initialize a turbo BertModel with smart batching from torch model.\n turbo_model = turbo_transformers.BertModelSmartBatch.from_torch(\n torch_model)\n\n # a batch of queries with different lengths.\n query_seq_len_list = [18, 2, 3, 51]\n input_list = []\n\n # generate random inputs. Of course you can use real data.\n for query_seq_len in query_seq_len_list:\n input_seq = torch.randint(low=0,\n high=cfg.vocab_size - 1,\n size=(1, query_seq_len),\n dtype=torch.long,\n device=test_device)\n input_list.append(input_seq)\n\n # start inference\n s_res = serial_bert_inference(torch_model, input_list)\n b_res = batch_bert_inference(turbo_model, input_list, query_seq_len_list)\n print(torch.max(torch.abs(b_res - s_res)))\n assert (torch.max(torch.abs(b_res - s_res)) < 1e-2)\n\n\nif __name__ == \"__main__\":\n if torch.cuda.is_available():\n test_smart_batch(True)\n test_smart_batch(False)\n","sub_path":"example/python/bert_smart_pad.py","file_name":"bert_smart_pad.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"515491070","text":"from meiga import Result\n\nfrom petisco import controller_handler, JwtConfig, HttpError\nfrom petisco.domain.entities.name import Name\nfrom petisco.domain.errors.given_input_is_not_valid_error import (\n GivenInputIsNotValidError,\n)\nfrom tests.integration.flask_app.toy_app.application.use_cases.use_case_builder import (\n UseCaseBuilder,\n)\n\n\ndef success_handler(result: Result):\n return {\"user_id\": result.value}, 200\n\n\nclass GivenInputIsNotValidHttpError(HttpError):\n def __init__(self, message: str = \"Given input is not valid\", code: int = 409):\n super(GivenInputIsNotValidHttpError, self).__init__(message=message, code=code)\n\n\ndef error_handler(result: Result):\n domain_error = result.value\n if isinstance(domain_error, GivenInputIsNotValidError):\n return GivenInputIsNotValidHttpError()\n\n\n@controller_handler(\n success_handler=success_handler,\n error_handler=error_handler,\n jwt_config=JwtConfig(token_type=\"ADMIN_TOKEN\"),\n)\ndef create_user(client_id, body, *args, **kwargs): # noqa: E501\n name = Name(body.get(\"name\")).to_result().handle()\n use_case = UseCaseBuilder.create_user()\n return use_case.execute(client_id=client_id, name=name)\n","sub_path":"tests/integration/flask_app/toy_app/application/controllers/create_user_controller.py","file_name":"create_user_controller.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"593718341","text":"#!/usr/bin/env python\nimport argparse\nimport numpy as np\nimport sys\nimport os\n\n# helices: G, H, I\n# beta: E, B\n# turn: T\n# bend : S\n# none: NonSeq\n\nsec_type = {\"G\" : \"helix\", \"H\" : \"helix\", \"I\" : \"helix\", \"T\": \"turn\", \"S\" : \"bend\", \"C\": \"misc\", \"NoSeq\": \"none\", \"*EOS*\" : \"beg\", \"*SOS*\" : \"end\"}\n\ndef scoring(proposed, actual):\n\t# 1 if same\n\t# one if within same set (see above)\n\tif len(proposed) > len(actual):\n\t\tx = proposed\n\t\ty = actual[:len(proposed)]\n\telse:\n\t\tx = proposed[:len(actual)]\n\t\ty = actual\n\tscore = 0\n\tfor i, j in zip(x, y):\n\t\tif i == j:\n\t\t\tscore += 1\n\t\telif sec_type[i] == sec_type[j]:\n\t\t\tscore += 0.5\n\t\telif (sec_type[i] == \"helix\" and sec_type[j] == \"turn\") or (sec_type[j] == \"helix\" and sec_type[i] == \"turn\"):\n\t\t\tscore += 0.25\n\treturn score, max(len(proposed), len(actual))\n\ndef valid_file(parser, arg):\n if arg and not os.path.exists(arg):\n parser.error('The file doesn\\'t exist: {}'.format(arg))\n else:\n return arg\n\n return args\n\n\nlst = raw_input().split()\n\ntotal_score = 0\ntotal_len = 0\ncount = 0\n# fi = sys.\n# print(\"FILE\", fi)\nfor line in sys.stdin.readlines():\n\tline = line.split()\n\tscore, lenx = scoring(line, lst[count])\n\ttotal_score += score\n\ttotal_len += lenx\n\t\t# print(score)\n\tcount += 1\nif total_len == 0:\n\ttotal_len = 1\nprint(\"{}\".format(100 * total_score / total_len))","sub_path":"Neural Machine Translation/scripts/convert_primsec.py","file_name":"convert_primsec.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"348961183","text":"from win32com.client import DispatchEx\r\nimport time\r\n\r\n\r\nsource_path = r'C:\\Users\\sunsh\\Documents\\Daily Approval Report\\Report\\New Report Charts.xlsx'\r\ndest_path = r'C:\\Users\\sunsh\\Documents\\Daily Approval Report\\Report\\New Report_strat_v2.xlsx'\r\nexcel = DispatchEx('Excel.Application')\r\nexcel.Visible = True\r\nexcel.AskToUpdateLinks = False\r\nexcel.EnableEvents = False\r\nexcel.DisplayAlerts = False\r\n\r\nwb_s = excel.Workbooks.Open(source_path)\r\nwb_d = excel.Workbooks.Open(dest_path)\r\n\r\n# sheet_names = [sheet.Name for sheet in wb_s.Sheets]\r\n# wb_s.Worksheets.Add(After=wb_s.Sheets(sheet_names[-1]))\r\n\r\n# for sheet in sheet_names:\r\n# ws = wb_s.Worksheets(sheet)\r\n# ws.Move(After=wb_d.Sheets(wb_d.Sheets.count))\r\n\r\nws = wb_s.Worksheets(1)\r\nws.Move(None, After=wb_d.Worksheets(1))\r\n\r\nws = wb_s.Worksheets(1)\r\nws.Move(None, After=wb_d.Worksheets(1))\r\n\r\nwb_d.Close(SaveChanges=True)\r\nwb_s.Close(SaveChanges=True)\r\n\r\nexcel.Quit()\r\ndel excel","sub_path":"Archive/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"583934633","text":"# create the movie class\nclass Movie():\n\t# define the initialization function a.k.a. constructor, passing in move details\n\tdef __init__(self, \n\t\t movie_title, \n\t\t movie_image_url, \n\t\t movie_trailer_url, \n\t\t movie_year, \n\t\t movie_director,\n\t\t movie_writers,\n\t\t movie_stars, \n\t\t movie_imdb_rating,\n\t\t movie_storyline):\n\t\tself.title = movie_title\n\t\tself.poster_image_url = movie_image_url\n\t\tself.trailer_youtube_url = movie_trailer_url\n\t\tself.year = movie_year \n\t\tself.director = movie_director \n\t\tself.writers = movie_writers\n\t\tself.stars = movie_stars\n\t\tself.imdb_rating = movie_imdb_rating\n\t\tself.storyline = movie_storyline","sub_path":"movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"20826196","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0006_auto_20150905_1857'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='build',\n name='status',\n field=models.CharField(max_length=16, default='scheduled', choices=[('scheduled', 'scheduled'), ('blocked', 'blocked'), ('running', 'running'), ('finished', 'finished')]),\n ),\n ]\n","sub_path":"jeeves/core/migrations/0007_auto_20150905_1932.py","file_name":"0007_auto_20150905_1932.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"514774737","text":"# coding: utf-8\nfrom __future__ import print_function\nimport sys\nimport types\nimport code\nimport json\n\nfrom six import class_types, StringIO\n\n\nclass AcquireStdOutAndStdErr(object):\n\n original_stdout = sys.stdout\n original_stderr = sys.stderr\n fake_stdout = StringIO()\n fake_stderr = StringIO()\n\n def __enter__(self, *args):\n sys.stdout = AcquireStdOutAndStdErr.fake_stdout\n sys.stderr = AcquireStdOutAndStdErr.fake_stderr\n\n def __exit__(self, *args):\n sys.stdout = AcquireStdOutAndStdErr.original_stdout\n sys.stderr = AcquireStdOutAndStdErr.original_stderr\n\n\ndef eval_(to_eval, namespace=None):\n if namespace is None:\n namespace = {}\n else:\n namespace = eval(namespace)\n\n namespace['__builtins__'] = []\n console = code.InteractiveConsole(locals=namespace)\n with AcquireStdOutAndStdErr():\n for function in namespace.get(\"functions\", []):\n for statement in function.split(\"\\\\n\"):\n console.push(statement.encode(\"utf-8\"))\n for statement in to_eval.split(\"\\n\"):\n if statement:\n console.push(statement)\n else:\n console.push('\\n')\n\n out = AcquireStdOutAndStdErr.fake_stdout.getvalue()\n error = AcquireStdOutAndStdErr.fake_stderr.getvalue()\n\n # remove functions and classes in namespace\n for key, value in namespace.items():\n if isinstance(value, types.FunctionType) \\\n or isinstance(value, class_types):\n del namespace[key]\n return {'out': out, 'namespace': json.dumps(namespace), 'error': error}\n\nif __name__ == \"__main__\":\n to_eval = sys.argv[1]\n namespace = sys.argv[2]\n print(json.dumps(eval_(to_eval, namespace=namespace)))\n","sub_path":"docker/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"515446775","text":"from oct_converter.readers import FDS\n\n# An example .fds file can be downloaded from the Biobank website:\n# https://biobank.ndph.ox.ac.uk/showcase/refer.cgi?id=30\nfilepath = '/home/mark/Downloads/eg_oct_fds(1).fds'\nfds = FDS(filepath)\n\noct_volume = fds.read_oct_volume() # returns an OCT volume with additional metadata if available\noct_volume.peek() # plots a montage of the volume\noct_volume.save('fds_testing.avi') # save volume as a movie\noct_volume.save('fds_testing.png') # save volume as a set of sequential images, fds_testing_[1...N].png\noct_volume.save_projection('projection.png')\n\nfundus_image = fds.read_fundus_image() # returns a Fundus image with additional metadata if available\nfundus_image.save('fds_testing_fundus.jpg')\n","sub_path":"examples/demo_fds_extraction.py","file_name":"demo_fds_extraction.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"346110803","text":"#!/usr/bin/env python3\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\n\"\"\"anova.py\n\nANOVA and related statistical tests written as exercise and reference.\nNote that a SciPy implementation of ANOVA exists and can be invoked with:\n scipy.stats.f_oneway(*args)\n\nThis module includes:\n anova_1way - One-way ANOVA; independent or correlated samples\n\n---------------------------\nAnalysis of Variance Primer\n---------------------------\nKey Idea:\n The null hypothesis (H0) posits no significant difference between sampled\n groups. We attribute deviations between groups to the different conditions,\n and we calculate the ratio of deviations between groups (MS_effect) and\n deviations within group (MS_error). If the ratio is large, that is,\n MS_effect >> MS_error, then we reject the null hypothesis at our chosen\n significance level.\n\nANOVA assumptions:\n 1. Independent variable is varied on a linear scale\n (e.g. 0 mg, 20 mg, 40 mg, ...).\n 2. The samples are drawn independently and randomly from the source\n population.\n 3. Source population distribution is approximately normal.\n 4. The samples have approximately equal variances.\n 5. \"Homogeneity of covariances\" for correlated samples.\n\nauthor: A. Y. Cho\ngithub: http://github.com/choyun1\ndate: May 28 2015\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import f\n\n\ndef anova_1way(X, correlated=False, plotting=False):\n \"\"\"One-way ANOVA for independent or correlated samples.\n\n X: np.array dataset; assumed to have following format:\n A B C ... <--- sampling conditions\n subj1 a1 b1 c1 ...\n subj2 a2 b2 c2 ...\n ... ...\n correlated: set True for correlated samples\n plotting: set True for the plot of F distribution\n \"\"\"\n if type(X) != np.ndarray:\n raise ValueError('input data must be a numpy array')\n if X.shape[0] < 2: raise ValueError('sample sizes not large enough')\n if len(X.shape) < 2: raise ValueError('not enough groups for ANOVA')\n\n n_g = X.shape[0]\n k = X.shape[1]\n n_t = k*n_g\n\n df_t = n_t - 1\n df_bg = k - 1\n df_wg = n_t - k\n\n SS_bg = sum(np.sum(X, axis=0)**2)/n_g - np.sum(X)**2/n_t\n SS_wg = sum(np.sum(X**2, axis=0) - np.sum(X, axis=0)**2/n_g)\n\n if not correlated:\n df_effect = df_bg\n df_error = df_wg\n\n MS_effect = SS_bg/df_effect\n MS_error = SS_wg/df_error\n\n else:\n df_effect = df_bg\n df_subj = n_g - 1\n df_error = df_wg - df_subj\n\n SS_subj = sum(np.sum(X, axis=1)**2)/k - np.sum(X)**2/n_t\n SS_error = SS_wg - SS_subj\n\n MS_effect = SS_bg/df_effect\n MS_error = SS_error/df_error\n\n F = MS_effect/MS_error\n p = f.pdf(F, df_effect, df_error)\n\n if plotting:\n alpha_05 = f.ppf(0.95, df_effect, df_error)\n alpha_01 = f.ppf(0.99, df_effect, df_error)\n x_max = f.ppf(0.999, df_effect, df_error)\n\n x = np.linspace(0.001, x_max, 5000)\n y = f.pdf(x, df_effect, df_error)\n\n plt.figure()\n ax = plt.subplot(111)\n line, = plt.plot(x, y, linewidth=2)\n plt.xlim = (0, x_max)\n plt.ylim = (0, 1)\n title_str = 'F probability density function (df=%d,%d)' %\\\n (df_effect, df_error)\n plt.title(title_str)\n plt.xlabel('X')\n plt.ylabel('Probability density')\n plt.annotate(r'$\\alpha=0.05$', xy=(alpha_05,0.1))\n plt.annotate(r'$\\alpha=0.01$', xy=(alpha_01,0.1))\n plt.show()\n\n print('\\nF(%.1f, %d, %d) = %.3f\\n' % (F, df_effect, df_error, p))\n return F, df_effect, df_error, p\n\n\n","sub_path":"anova.py","file_name":"anova.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"67628557","text":"from collections import deque\n\nINPUT_PATH = 'input-small.in'\n\ndef main():\n test_cases = parse_input(INPUT_PATH)\n solutions = []\n for test_case in test_cases:\n solution = solve(test_case)\n solutions.append(solution)\n output_solutions(solutions)\n\n\ndef parse_input(path):\n with open(path) as f:\n n = int(f.readline())\n lines = f.read().split()\n test_cases = [tuple(bool(char == '+') for char in line)\n for line in lines]\n assert n == len(test_cases)\n return test_cases\n\n\ndef output_solutions(solutions):\n with open('output', 'w') as f:\n for i, solution in enumerate(solutions, 1):\n f.write('Case #{i}: {result}\\n'.format(i=i, result=solution))\n\n\ndef solve(start):\n steps = bfs(start, generate_neighbors, is_goal)\n return steps\n\n\ndef bfs(start, generate_neighbors, is_goal):\n \"\"\" Return number of steps to get to the goal\n \"\"\"\n queue = deque([(start, 0)])\n seen = set([start])\n while True:\n state, steps = queue.popleft()\n if is_goal(state):\n return steps\n for neighbor in generate_neighbors(state):\n if neighbor not in seen:\n queue.append((neighbor, steps+1))\n seen.add(neighbor)\n\n\n# optimized version, only generate splits on True/False borders\ndef generate_neighbors(state):\n neighbors = []\n for k in range(1, len(state)+1):\n if k < len(state) and state[k - 1] == state[k]:\n continue\n neighbor = tuple((not face) for face in reversed(state[:k])) + state[k:]\n neighbors.append(neighbor)\n return neighbors\n\n\n# not optimized version:\n#def generate_neighbors(state):\n# neighbors = []\n# for k in range(1, len(state)+1):\n# neighbor = tuple((not face) for face in reversed(state[:k])) + state[k:]\n# neighbors.append(neighbor)\n# return neighbors\n\n\ndef is_goal(state):\n return all(state)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"codes/CodeJamCrawler/CJ/16_0_2_arteffi_problem2.py","file_name":"16_0_2_arteffi_problem2.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"438174134","text":"#!/usr/bin/env python\n#\n#mergefq.py takes a pair of matched fastq files (reads1 and reads2, respectively)\n# and merges them so that each read1 is followed by its read2 partner. The output\n# is printed to files of chunksize read pairs each, named outflable-mergedreads-number.\n#\nfrom Bio import SeqIO\nimport itertools\nimport sys\nimport os\n\ndef merge_fastq(fastq_path1, fastq_path2, outflabel, chunksize):\n chunksize = int(chunksize)\n i = -1\n fnlabel = 0\n fastq_iter1 = SeqIO.parse(open(fastq_path1),\"fastq\")\n fastq_iter2 = SeqIO.parse(open(fastq_path2),\"fastq\")\n for rec1, rec2 in itertools.izip(fastq_iter1, fastq_iter2):\n i += 1\n if i%chunksize == 0 :\n if i > 0 :\n outfile.close()\n fnlabel += 1\n outfname = \"%s-mergedreads-%d\" % (outflabel, fnlabel)\n outfile = open(outfname,\"w\")\n\n SeqIO.write([rec1,rec2], outfile, \"fastq\")\n outfile.close()\n\nif __name__ == '__main__':\n merge_fastq(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])\n","sub_path":"bgRAMOSE-specific/DDNscripts/mergefq.py","file_name":"mergefq.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"609016029","text":"import numpy as np\nimport sys\nimport tensorflow as tf\nimport sys, os,cv2\nfrom sklearn.utils import shuffle\nfrom scipy.misc import imread,imresize\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import OneHotEncoder\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nimport imgaug as ia\nfrom skimage.color import rgba2rgb\nnp.set_printoptions(precision=2)\n\n# old_v = tf.logging.get_verbosity()\n# tf.logging.set_verbosity(tf.logging.ERROR)\n# from tensorflow.examples.tutorials.mnist import input_data\n# plt.style.use('seaborn-white')\n# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\ndef neg_squared_euc_dists(X):\n \"\"\"Compute matrix containing negative squared euclidean\n distance for all pairs of points in input matrix X\n\n # Arguments:\n X: matrix of size NxD\n # Returns:\n NxN matrix D, with entry D_ij = negative squared\n euclidean distance between rows X_i and X_j\n \"\"\"\n # Math? See https://stackoverflow.com/questions/37009647\n sum_X = np.sum(np.square(X), 1)\n D = np.add(\n np.add(-2 * np.dot(X, X.T), \n sum_X).T, \n sum_X)\n return -D\n\ndef softmax(X, diag_zero=True):\n \"\"\"Take softmax of each row of matrix X.\"\"\"\n\n # Subtract max for numerical stability\n e_x = np.exp(X - np.max(X, axis=1).reshape([-1, 1]))\n\n # We usually want diagonal probailities to be 0.\n if diag_zero:\n np.fill_diagonal(e_x, 0.)\n\n # Add a tiny constant for stability of log we take later\n e_x = e_x + 1e-8 # numerical stability\n\n return e_x / e_x.sum(axis=1).reshape([-1, 1])\n\n\n\ndef binary_search(eval_fn, target, tol=1e-10, max_iter=10000, lower=1e-20, upper=1000.):\n \"\"\"Perform a binary search over input values to eval_fn.\n \n # Arguments\n eval_fn: Function that we are optimising over.\n target: Target value we want the function to output.\n tol: Float, once our guess is this close to target, stop.\n max_iter: Integer, maximum num. iterations to search for.\n lower: Float, lower bound of search range.\n upper: Float, upper bound of search range.\n # Returns:\n Float, best input value to function found during search.\n \"\"\"\n for i in range(max_iter):\n guess = (lower + upper) / 2.\n val = eval_fn(guess)\n if val > target:\n upper = guess\n else:\n lower = guess\n if np.abs(val - target) <= tol:\n break\n return guess\n\ndef calc_perplexity(prob_matrix):\n \"\"\"Calculate the perplexity of each row \n of a matrix of probabilities.\"\"\"\n entropy = -np.sum(prob_matrix * np.log2(prob_matrix), 1)\n perplexity = 2 ** entropy\n return perplexity\n \ndef calc_prob_matrix(distances, sigmas=None):\n \"\"\"Convert a distances matrix to a matrix of probabilities.\"\"\"\n if sigmas is not None:\n two_sig_sq = 2. * np.square(sigmas.reshape((-1, 1)))\n return softmax(distances / two_sig_sq)\n else:\n return softmax(distances)\n\ndef perplexity(distances, sigmas):\n \"\"\"Wrapper function for quick calculation of \n perplexity over a distance matrix.\"\"\"\n return calc_perplexity(calc_prob_matrix(distances, sigmas))\n\n\ndef find_optimal_sigmas(distances, target_perplexity):\n \"\"\"For each row of distances matrix, find sigma that results\n in target perplexity for that role.\"\"\"\n sigmas = [] \n # For each row of the matrix (each point in our dataset)\n for i in range(distances.shape[0]):\n # Make fn that returns perplexity of this row given sigma\n eval_fn = lambda sigma: perplexity(distances[i:i+1, :], np.array(sigma))\n\n # Binary search over sigmas to achieve target perplexity\n correct_sigma = binary_search(eval_fn, target_perplexity)\n\n # Append the resulting sigma to our output array\n sigmas.append(correct_sigma)\n return np.array(sigmas)\n\n\ntemp = np.array([\n [1,1],\n [2,2],\n [1,1]\n])\n\ntarget_perplexity=20\ndistnace = neg_squared_euc_dists(temp)\nsigmas = find_optimal_sigmas(distnace, target_perplexity)\n\nprint(sigmas)\n\nsys.exit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef q_joint(Y):\n \"\"\"Given low-dimensional representations Y, compute\n matrix of joint probabilities with entries q_ij.\"\"\"\n # Get the distances from every point to every other\n distances = neg_squared_euc_dists(Y)\n # Take the elementwise exponent\n exp_distances = np.exp(distances)\n # Fill diagonal with zeroes so q_ii = 0\n np.fill_diagonal(exp_distances, 0.)\n # Divide by the sum of the entire exponentiated matrix\n return exp_distances / np.sum(exp_distances), None\n\n\ndef p_conditional_to_joint(P):\n \"\"\"Given conditional probabilities matrix P, return\n approximation of joint distribution probabilities.\"\"\"\n return (P + P.T) / (2. * P.shape[0])\n\ndef p_joint(X, target_perplexity):\n \"\"\"Given a data matrix X, gives joint probabilities matrix.\n\n # Arguments\n X: Input data matrix.\n # Returns:\n P: Matrix with entries p_ij = joint probabilities.\n \"\"\"\n # Get the negative euclidian distances matrix for our data\n distances = neg_squared_euc_dists(X)\n # Find optimal sigma for each row of this distances matrix\n sigmas = find_optimal_sigmas(distances, target_perplexity)\n # Calculate the probabilities based on these optimal sigmas\n p_conditional = calc_prob_matrix(distances, sigmas)\n # Go from conditional to joint probabilities matrix\n P = p_conditional_to_joint(p_conditional)\n return P\n\n\ndef symmetric_sne_grad(P, Q, Y, _):\n \"\"\"Estimate the gradient of the cost with respect to Y\"\"\"\n pq_diff = P - Q # NxN matrix\n pq_expanded = np.expand_dims(pq_diff, 2) #NxNx1\n y_diffs = np.expand_dims(Y, 1) - np.expand_dims(Y, 0) #NxNx2\n grad = 4. * (pq_expanded * y_diffs).sum(1) #Nx2\n return grad\n\ndef categorical_scatter_2d(X2D, class_idxs, ms=3, ax=None, alpha=0.1, \n legend=True, figsize=None, show=False, \n savename=None):\n ## Plot a 2D matrix with corresponding class labels: each class diff colour\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize)\n #ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling\n classes = list(np.unique(class_idxs))\n markers = 'os' * len(classes)\n colors = plt.cm.rainbow(np.linspace(0,1,len(classes)))\n\n for i, cls in enumerate(classes):\n mark = markers[i]\n ax.plot(X2D[class_idxs==cls, 0], X2D[class_idxs==cls, 1], marker=mark, \n linestyle='', ms=ms, label=str(cls), alpha=alpha, color=colors[i],\n markeredgecolor='black', markeredgewidth=0.4)\n if legend:\n ax.legend()\n \n if savename is not None:\n plt.tight_layout()\n plt.savefig(savename)\n \n if show:\n plt.show()\n \n return ax\n\ndef estimate_sne(X, y, P, rng, num_iters, q_fn, grad_fn, learning_rate,\n momentum, plot):\n \"\"\"Estimates a SNE model.\n\n # Arguments\n X: Input data matrix.\n y: Class labels for that matrix.\n P: Matrix of joint probabilities.\n rng: np.random.RandomState().\n num_iters: Iterations to train for.\n q_fn: Function that takes Y and gives Q prob matrix.\n plot: How many times to plot during training.\n # Returns:\n Y: Matrix, low-dimensional representation of X.\n \"\"\"\n\n # Initialise our 2D representation\n Y = rng.normal(0., 0.0001, [X.shape[0], 2])\n\n # Initialise past values (used for momentum)\n if momentum:\n Y_m2 = Y.copy()\n Y_m1 = Y.copy()\n\n # Start gradient descent loop\n for i in range(num_iters):\n\n # Get Q and distances (distances only used for t-SNE)\n Q, distances = q_fn(Y)\n # Estimate gradients with respect to Y\n grads = grad_fn(P, Q, Y, distances)\n\n # Update Y\n Y = Y - learning_rate * grads\n if momentum: # Add momentum\n Y += momentum * (Y_m1 - Y_m2)\n # Update previous Y's for momentum\n Y_m2 = Y_m1.copy()\n Y_m1 = Y.copy()\n\n # # Plot sometimes\n # if plot and i % (num_iters / plot) == 0:\n # categorical_scatter_2d(Y, y, alpha=1.0, ms=6,\n # show=True, figsize=(9, 6))\n\n return Y\n\n# Set global parameters\nNUM_POINTS = 200 # Number of samples from MNIST\nCLASSES_TO_USE = [0, 1, 8] # MNIST classes to use\nPERPLEXITY = 10 \nSEED = 1 # Random seed\nMOMENTUM = 0.9\nLEARNING_RATE = 0.9\nNUM_ITERS = 3000 # Num iterations to train for\nTSNE = False # If False, Symmetric SNE\nNUM_PLOTS = 5 # Num. times to plot in training\n\n\ndef main():\n # numpy RandomState for reproducibility\n rng = np.random.RandomState(SEED)\n\n mnist = input_data.read_data_sets('../../Dataset/MNIST/', one_hot=True)\n train, test = tf.keras.datasets.mnist.load_data()\n x_data, train_label, y_data, test_label = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n\n\n X = x_data[:500]\n train_label = train_label[:500]\n\n # # Load the first NUM_POINTS 0's, 1's and 8's from MNIST\n # X, y = load_mnist('datasets/',\n # digits_to_keep=CLASSES_TO_USE,\n # N=NUM_POINTS)\n\n # Obtain matrix of joint probabilities p_ij\n P = p_joint(X, PERPLEXITY)\n\n # Fit SNE or t-SNE\n Y = estimate_sne(X, train_label, P, rng,\n num_iters=NUM_ITERS,\n q_fn=q_tsne if TSNE else q_joint,\n grad_fn=tsne_grad if TSNE else symmetric_sne_grad,\n learning_rate=LEARNING_RATE,\n momentum=MOMENTUM,\n plot=NUM_PLOTS)\n\n color_dict = {\n 0:'red',\n 1:'blue',\n 2:'green',\n 3:'yellow',\n 4:'purple',\n 5:'grey',\n 6:'black',\n 7:'violet',\n 8:'silver',\n 9:'cyan',\n }\n\n color_mapping = [color_dict[x] for x in np.argmax(train_label,1) ]\n plt.scatter(Y[:,0],Y[:,1],c=color_mapping)\n plt.show()\n\nmain()\n\n# -- end code --","sub_path":"NeuralNetwork/TSNE/tmep/z_numpy.py","file_name":"z_numpy.py","file_ext":"py","file_size_in_byte":10028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"527613253","text":"# Written by *** and Eric Martin for COMP9021\n\n\n'''\nPrompts the user for two strictly positive integers, numerator and denominator.\n\nDetermines whether the decimal expansion of numerator / denominator is finite or infinite.\n\nThen computes integral_part, sigma and tau such that numerator / denominator is of the form\nintegral_part . sigma tau tau tau ...\nwhere integral_part in an integer, sigma and tau are (possibly empty) strings of digits,\nand sigma and tau are as short as possible.\n'''\n\n\nimport sys\nfrom math import gcd\n\n\ntry:\n numerator, denominator = input('Enter two strictly positive integers: ').split()\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\ntry:\n numerator, denominator = int(numerator), int(denominator)\n if numerator <= 0 or denominator <= 0:\n raise ValueError\nexcept ValueError:\n print('Incorrect input, giving up.')\n sys.exit()\n\ndef gcd(m, n):\n while m != n:\n if m > n:\n m = m - n\n else:\n n = n - m\n return m\ngcd1 = gcd(numerator, denominator)\np = [-1] * 100000000000\nq = [-1] * 100000000000\n#p = [-1] * (numerator // gcd1) * (denominator // gcd1)\n#q = [-1] * (numerator // gcd1) * (denominator // gcd1)\n#p = [-1] * numerator\n#q = [-1] * numerator\nn = numerator // gcd1\nm = denominator // gcd1\n\nt = 0\nhas_finite_expansion = False\nintegral_part = 0\nsigma = ''\ntau = ''\n\nif (numerator < denominator):\n o = n\n while (p[o] == -1):\n p[o] = t\n t += 1\n o = o * 10\n q[t] = o // m\n o = o % m\n if p[o] != 0:\n sigma = str(q[1: p[o]+1])\n tau = str(q[p[o]+1: t+1])\n if q[t] == 0:\n has_finite_expansion = True\n tau = ''\nelif (numerator > denominator):\n integral_part = n // m\n new_n = n - integral_part * m\n o = new_n\n while (p[o] == -1):\n p[o] = t\n t += 1\n o = o * 10\n q[t] = o // m\n o = o % m\n if p[o] != 0:\n sigma = str(q[1: p[o]+1])\n tau = str(q[p[o]+1: t+1])\n if q[t] == 0:\n has_finite_expansion = True\n tau = ''\n \nelse:\n integral_part = 1\n has_finite_expansion = True\n \n \n \n\n\n\n\n\n# Replace this comment with your code\n\nif has_finite_expansion:\n print(f'\\n{numerator} / {denominator} has a finite expansion')\nelse:\n print(f'\\n{numerator} / {denominator} has no finite expansion')\nif not tau:\n if not sigma:\n print(f'{numerator} / {denominator} = {integral_part}')\n else:\n print(f'{numerator} / {denominator} = {integral_part}.{sigma}')\nelse:\n print(f'{numerator} / {denominator} = {integral_part}.{sigma}({tau})*')\n\n","sub_path":"quiz2.py","file_name":"quiz2.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"153988506","text":"from sqlalchemy.exc import IntegrityError\nfrom main import db\nfrom models import User, Recipe, Ingredient, Usersession, Association\n\ndb.create_all()\n\ndef add_dummy():\n user = User('Atest', 'a@a.co', 'aaaaaa')\n db.session.add(user)\n\n steps = {\n 1: 'Butter both slices of bread on one side with little butter.',\n 2: 'Put on one buttered side the ham and the pineapple. Garnish with little parsley.',\n 3: 'Cover with the cheese and finally the other slice of bread with the greased side in.',\n 4: 'Heat the toast and grill iron (or use a covered baking pan) and grill the tosti until it\\'s golden brown and the cheese has melted.',\n 5: 'Serve with tomato ketchup or curry sauce.'\n }\n recipe = Recipe('Tosti', 'Just a tosti', steps)\n\n ingredients = ['butter', 'ham', 'pineapple', 'parsley', 'cheese', 'bread']\n for i, ingredient in enumerate(ingredients):\n a = Association(amount=500, unit='mL')\n a.child = Ingredient(ingredient)\n recipe.ingredients.append(a)\n\n db.session.add(recipe)\n\n db.session.commit()\n\nadd_dummy()\n","sub_path":"init_db.py","file_name":"init_db.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"63500927","text":"import csv\n\n\nclass tsv_prep(object):\n \"\"\"Returns an iterator with tsv file content\"\"\"\n\n def __init__(self, filename):\n self.thisfile = filename\n self.filecontents = self.fid_read(filename)\n self.start = -1\n self.stop = len(self.filecontents)\n\n def __iter__(self):\n self.current = self.start\n return self\n\n def next(self):\n self.current += 1\n if self.current < self.stop:\n return self.filecontents[self.current]\n else:\n raise StopIteration\n\n def fid_read(self, filename):\n with open(filename, 'rb') as fid:\n reader = csv.reader(fid, dialect='excel-tab')\n file_content = [row for row in reader]\n return file_content\n","sub_path":"scripts/tsv_prep.py","file_name":"tsv_prep.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"13849463","text":"\"\"\"\n========\nDatasets\n========\n\nHow to list and download datasets.\n\"\"\"\n\nimport openml\nimport pandas as pd\n\n############################################################################\n# List datasets\n# =============\n\nopenml_list = openml.datasets.list_datasets() # returns a dict\n\n# Show a nice table with some key data properties\ndatalist = pd.DataFrame.from_dict(openml_list, orient='index')\ndatalist = datalist[[\n 'did', 'name', 'NumberOfInstances',\n 'NumberOfFeatures', 'NumberOfClasses'\n]]\n\nprint(\"First 10 of %s datasets...\" % len(datalist))\ndatalist.head(n=10)\n\n############################################################################\n# Exercise 1\n# **********\n#\n# * Find datasets with more than 10000 examples.\n# * Find a dataset called 'eeg_eye_state'.\n# * Find all datasets with more than 50 classes.\ndatalist[datalist.NumberOfInstances > 10000\n ].sort_values(['NumberOfInstances']).head(n=20)\n############################################################################\ndatalist.query('name == \"eeg-eye-state\"')\n############################################################################\ndatalist.query('NumberOfClasses > 50')\n\n############################################################################\n# Download datasets\n# =================\n\n# This is done based on the dataset ID ('did').\ndataset = openml.datasets.get_dataset(68)\n\n# Print a summary\nprint(\"This is dataset '%s', the target feature is '%s'\" %\n (dataset.name, dataset.default_target_attribute))\nprint(\"URL: %s\" % dataset.url)\nprint(dataset.description[:500])\n\n############################################################################\n# Get the actual data.\n#\n# Returned as numpy array, with meta-info (e.g. target feature, feature names,...)\nX, y, attribute_names = dataset.get_data(\n target=dataset.default_target_attribute,\n return_attribute_names=True,\n)\neeg = pd.DataFrame(X, columns=attribute_names)\neeg['class'] = y\nprint(eeg[:10])\n\n############################################################################\n# Exercise 2\n# **********\n# * Explore the data visually.\neegs = eeg.sample(n=1000)\n_ = pd.plotting.scatter_matrix(\n eegs.iloc[:100, :4],\n c=eegs[:100]['class'],\n figsize=(10, 10),\n marker='o',\n hist_kwds={'bins': 20},\n alpha=.8,\n cmap='plasma'\n)","sub_path":"examples/datasets_tutorial.py","file_name":"datasets_tutorial.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"620472333","text":"import numpy as np\nimport numpy.testing as npt\nimport pytest\n\nfrom pulse2percept.models import FadingTemporal\nfrom pulse2percept.stimuli import Stimulus, MonophasicPulse, BiphasicPulse\nfrom pulse2percept.percepts import Percept\nfrom pulse2percept.utils import FreezeError\n\n\ndef test_FadingTemporal():\n model = FadingTemporal()\n # User can set their own params:\n model.dt = 0.1\n npt.assert_equal(model.dt, 0.1)\n model.build(dt=1e-4)\n npt.assert_equal(model.dt, 1e-4)\n # User cannot add more model parameters:\n with pytest.raises(FreezeError):\n model.rho = 100\n\n # Nothing in, None out:\n npt.assert_equal(model.predict_percept(None), None)\n\n # Zero in = zero out:\n stim = BiphasicPulse(0, 1)\n percept = model.predict_percept(stim, t_percept=[0, 1, 2])\n npt.assert_equal(isinstance(percept, Percept), True)\n npt.assert_equal(percept.shape, (1, 1, 3))\n npt.assert_almost_equal(percept.data, 0)\n\n # Can't request the same time more than once (this would break the Cython\n # loop, because `idx_frame` is incremented after a write; also doesn't\n # make much sense):\n with pytest.raises(ValueError):\n stim = Stimulus(np.ones((1, 100)))\n model.predict_percept(stim, t_percept=[0.2, 0.2])\n\n # Simple decay for single cathodic pulse:\n model = FadingTemporal(tau=1).build()\n stim = MonophasicPulse(-1, 1, stim_dur=10)\n percept = model.predict_percept(stim, np.arange(stim.duration))\n npt.assert_almost_equal(percept.data.ravel()[:3], [0, 0.633, 0.232],\n decimal=3)\n npt.assert_almost_equal(percept.data.ravel()[-1], 0, decimal=3)\n\n # But all zeros for anodic pulse:\n stim = MonophasicPulse(1, 1, stim_dur=10)\n percept = model.predict_percept(stim, np.arange(stim.duration))\n npt.assert_almost_equal(percept.data, 0)\n\n # tau cannot be negative:\n with pytest.raises(ValueError):\n FadingTemporal(tau=-1).build()\n","sub_path":"pulse2percept/models/tests/test_temporal.py","file_name":"test_temporal.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"253057342","text":"import os\nfrom os.path import join\nimport numpy as np\nfrom collections import OrderedDict\nfrom ase.atoms import Atoms, Atom\nfrom ase.visualize import view\n\nfrom CalcTroll.Core.Flags import NOT_STARTED, FAILED, DONE\nfrom CalcTroll.Plugins.Programs.EHTParameters import EHTBasisSet\nfrom CalcTroll.Plugins.STM.Parameters import Topographic\nfrom CalcTroll import API\n\n\ndef aseToGreen(atoms, names, EK_data=None):\n script = '%s%s%s'%('%lattice\\n', ' label= Gamma\\n', '%end_lattice\\n')\n for electrode in atoms.regions():\n script += latticeBlock(electrode)\n script += '\\n'\n script += block(electrode, names[electrode.indices()], EK_data=EK_data)\n script += '\\n\\n'\n\n return script\n\ndef latticeBlock(electrode):\n if len(electrode.atoms())==0:\n return ''\n\n atoms = electrode.atoms()\n vectors = atoms.cell[atoms.pbc]\n if len(vectors) == 0:\n return ''\n\n label = electrode.name()\n vector_block = ' %vectors ! Lattice vectors\\n'\n\n for i in range(len(vectors)):\n vector = vectors[i]\n if abs(vector[i]) > 1e-5:\n vector = np.sign(vector[i])*vector\n vector = np.around(vector + 1e-8, 8)\n\n x, y, z = vector\n vector_block += ' vector #%d: %.6f %.6f %.6f\\n'%(i+1, x, y, z)\n vector_block += ' %end_vectors'\n\n lattice_block = \"\"\" label = %s ! Lattice label\n ndim = %d ! Dimensionality of lattice\n vec_unit = A ! Lattice vec. in alat units\n%s\n\"\"\"%(label, len(vectors), vector_block)\n script = '%s%s%s'%('%lattice\\n', lattice_block, '%end_lattice\\n')\n\n return script\n\ndef block(electrode, names, EK_data=None):\n label = electrode.name()\n atoms = electrode.atoms()\n if len(atoms)==0:\n return ''\n\n atoms_block = ' %atoms\\n'\n for i in range(len(atoms)):\n x, y, z = atoms[i].position\n symbol = '%s'%(names[i])\n atoms_block += ' at #%d : %.6f %.6f %.6f %s\\n'%(i + 1, x, y, z, symbol)\n atoms_block += ' %end_atoms'\n\n if electrode.pbc() == (False, False, False):\n lattice_label = 'Gamma'\n else:\n lattice_label = label\n\n if electrode.pbc() == (True, True, True):\n type_label = 'uc'\n elif not electrode.semiInfiniteDirection() is None:\n type_label = 'bulk'\n else:\n type_label = 'pl'\n\n script = \"\"\"%block\"\"\" + \"\"\"\n label = %s\n xyz_file = %s\n type = %s\n lattice = %s\n r_format = xyz S\n%s\"\"\"%(label, label, type_label, lattice_label, atoms_block)\n if not EK_data is None:\n script += \"\"\"\n EK_data_file = %s\"\"\"%EK_data\n script += \"\"\"\n%end_block\n\"\"\"\n return script\n\ndef greenXYZToASE(filename):\n with open(filename, 'r') as f:\n f.readline().strip()\n f.readline().strip()\n symbols = []\n for line in f:\n line = [entry for entry in line.strip().split(' ') if len(entry) > 0]\n symbol = line[0].split('_')[0]\n position = map(float, line[1:])\n symbols.append(Atom(symbol, position))\n atoms = Atoms(symbols=symbols)\n\n return atoms\n\ndef makeCollectBlock(name, blocks):\n script = \"\"\"\n%block\"\"\" + \"\"\"\n label = %s\"\"\"%name + \"\"\"\n %stack\"\"\"\n for i, block in enumerate(blocks[:-1]):\n script += \"\"\"\n BL #%d : %s\n vec_b%d #%d : 0.00 0.0 0.0 A\"\"\"%(i+1, block, i+1, i+2)\n script += \"\"\"\\n BL #%d : %s\"\"\"%(len(blocks), blocks[-1])\n\n script += \"\"\"\n %end_stack\"\"\" + \"\"\"\n xyz_file = %s xyz\n stop = F\"\"\"%name + \"\"\"\n%end_block\n\"\"\"\n return script\n\n\ndef scriptBlock(block, content):\n string = '%' + block + '\\n'\n string += content + '\\n'\n string += '%end_' + block\n\n return string\n\ndef getSpecies(atoms, basis_sets):\n symbols = np.array(atoms.get_chemical_symbols())\n tags = atoms.tagStrings()\n species_identifiers = np.zeros(len(atoms), dtype=int)\n species = OrderedDict()\n i = 1\n for basis_set in basis_sets:\n tag = basis_set['tag']\n symbol = basis_set['symbol']\n mask = symbols == symbol\n if not tag is None:\n if tag in tags:\n tag = atoms.tag(tag)\n mask2 = tag.mask()\n mask = np.logical_and(mask, mask2)\n else:\n mask = np.zeros(len(atoms), bool)\n\n if sum(mask) > 0:\n species[i] = basis_set\n species_identifiers[mask] = i\n i += 1\n\n return species, species_identifiers\n\ndef scriptEHT(atoms, basis_sets):\n h_script = 'hij = eht1'\n full_script = scriptBlock('hamiltonian', h_script) + '\\n'*2\n species, species_identifiers = getSpecies(atoms, basis_sets)\n\n for basis_set in species.values():\n maxshell = basis_set.largestPrincipal()\n symbol = basis_set['symbol']\n name = symbol\n if not basis_set['tag'] is None:\n name += '_%s'%basis_set['tag']\n\n lmax = basis_set.largestAngular()\n valence = {'Ge':4, 'Si':4, 'C':4, 'H':1, 'W':6, 'Ag':10}[symbol]\n script = '%s %d %d '%(name, valence, lmax)\n script += ' '.join(['1']*(lmax+1))\n script += '\\ne_unit = eV\\n'\n onsites = [orbital['onsite'] for orbital in basis_set['orbitals']]\n ANG_LETTER = {0:'s', 1:'p', 2:'d', 3:'f'}\n onsite_string = ' '.join(['%s %.4f'%(ANG_LETTER[i], onsites[i]) for i in range(lmax + 1)])\n script += scriptBlock('e_onsite', onsite_string)\n script += '\\n'\n sto_block = ''\n for orbital in basis_set['orbitals']:\n string = '%d '%len(orbital)\n exponents = orbital['exponents']\n coefficients = orbital['coefficients']\n for i in range(len(orbital)):\n string += '%d %.4f %.4f '%(orbital['principal_number'],\n exponents[i],\n coefficients[i],\n )\n string += '\\n'\n sto_block += string\n sto_block = sto_block[:-1]\n script += scriptBlock('sto', sto_block)\n script += '\\nkeht1 = %.3f'%basis_set['wh_constant']\n script = scriptBlock('element', script)\n full_script += script\n full_script += '\\n\\n'\n\n return full_script\n\ndef scriptEHTHiroyo(atoms):\n script = \"\"\"%hamiltonian\n hij = eht1\n%end_hamiltonian\n\n%element ! Val lmax n_zeta(0:lmax)\n H_-2 1 0 1\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 1 -13.6000 1.3000 1.0000 0.00000 0.00000\n %end_basis\n keht1 = 1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n W 6 0 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 6 -10.51620 2.30427 0.80244 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n Ge_1 4 2 1 1 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 4 -19.94801 2.43232 1.00000 0.00000 0.00000\n p_1 : 4 -11.89222 1.74963 0.90000 0.90000 0.10000\n d_1 : 3 -4.85218 0.76992 1.00000 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n Ge_-1 4 2 1 1 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 4 -18.14801 2.43232 1.00000 0.00000 0.00000\n p_1 : 4 -11.89222 1.74963 1.00000 0.00000 0.00000\n d_1 : 3 -4.85218 1.29992 1.00000 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n Ge_-2 4 2 1 1 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 4 -19.94801 2.43232 1.00000 0.00000 0.00000\n p_1 : 4 -11.89222 1.74963 1.00000 0.00000 0.00000\n d_1 : 3 -4.85218 1.29992 1.00000 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n Ge_-3 4 2 1 1 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 4 -19.94801 2.43232 1.00000 0.00000 0.00000\n p_1 : 4 -11.89222 1.74963 1.00000 0.00000 0.00000\n d_1 : 3 -4.85218 0.86992 1.00000 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\n%element ! Val lmax n_zeta(0:lmax)\n Ge_-4 4 2 1 1 1\n spin = F\n e_unit = eV\n %basis\n # L_zeta n E-onsite Exp1 Coef1 Exp2 Coef2\n s_1 : 4 -19.94801 2.43232 1.00000 0.00000 0.00000\n p_1 : 4 -11.89222 1.74963 1.00000 0.00000 0.00000\n d_1 : 3 -5.95218 0.86992 1.00000 0.00000 0.00000\n %end_basis\n keht1=1.750\n%end_element\n\"\"\"\n return script\n\nclass Green(API.Program):\n def __init__(self, basis_set=EHTBasisSet(), default_probe=None):\n self.__default_probe = default_probe\n\n def identifier(self, mode):\n return mode.identifier()\n\n def defaultProbe(self, probe=None):\n if probe is None:\n return self.__default_probe\n else:\n return probe\n\n def path(self):\n return self.name()\n\n def neededFiles(self):\n return ['*.psf', '*.fdf', '*.in', '*.gin']\n\n def makeCommands(self, form):\n one = form%'RUN'\n two = 'rgreen_plot RUN'\n\n return [one, two]\n\n @classmethod\n def checkIfFinished(cls, filename, input_dump=None):\n if not os.path.exists(filename):\n return NOT_STARTED\n\n with open(filename, 'r') as f:\n for line in f:\n if 'Termination \"Daguten\" ....' in line:\n return DONE\n\n return FAILED\n\n def writeAtoms(self, runfile, atoms, mode):\n substrate = list(atoms.tag('substrate').picker())\n\n # Collect atoms belonging to surface of substrate in one block\n if len(substrate) > 2:\n main_tag = atoms.tag(substrate[1])\n for tag_name in substrate[2:]:\n indices = atoms.tag(tag_name).indices()\n main_tag.addToTag(indices)\n atoms.removeTag(tag_name)\n\n substrate = substrate[:2]\n\n tip = list(atoms.tag('probe').picker())\n tip.reverse()\n blocks = [substrate, tip]\n\n with open(runfile, 'w') as f:\n f.write(self.writeDefaults(atoms, mode))\n f.write(self.writeEHTHamiltonian(atoms))\n f.write(self.aseToStructure(atoms))\n f.write(self.writeBigBlocks(blocks))\n f.write(self.writeScan(mode=mode, lattice=blocks[0][1]))\n\n graphic_file = join(os.path.dirname(runfile), 'RUN.gin')\n with open(graphic_file, 'w') as f:\n f.write(self.writeGraphic(atoms, mode=mode))\n\n @classmethod\n def writeStoreData(cls, runfile, atoms, fdf_file, ef):\n fdf_file = os.path.relpath(fdf_file, runfile)\n with open(runfile, 'w') as f:\n f.write(cls.writeDefaults(atoms))\n f.write(cls.writeHamiltonian(fdf_file=fdf_file))\n f.write(cls.writeFitBlock(fdf_file=fdf_file, ef=ef))\n f.write('%bands\\n')\n f.write(' EK_data = T\\n')\n f.write('%end_bands\\n')\n f.write('%dos\\n')\n f.write(' type = l resolved k\\n')\n f.write('%end_dos\\n')\n\n def writeFit(cls, runfile, atoms):\n with open(runfile, 'w') as f:\n f.write(cls.writeDefaults(atoms))\n f.write(cls.writeEHTHamiltonian(atoms))\n f.write(cls.aseToStructure(atoms, EK_data='../siesta.EK_data'))\n f.write(cls.writeFitting())\n\n\n @classmethod\n def writeHamiltonian(cls, fdf_file):\n script = \"\"\"%hamiltonian\"\"\" + \"\"\"\n hij = siesta\n elements_file = %s\"\"\"%fdf_file + \"\"\"\n%end_hamiltonian\n\"\"\"\n return script\n\n @classmethod\n def writeFitBlock(cls, fdf_file, ef):\n script = \"\"\"%block\"\"\" + \"\"\"\n fdf_file = %s DM F EF %5f\"\"\"%(fdf_file, ef) + \"\"\"\n\n %include:\n file : fcc_EK_fit.k\n %end_include:\n%end_block\n\"\"\"\n return script\n\n @classmethod\n def writeFitting(cls):\n script = \"\"\"\n--------------------------- Calculation options ------------------------\n# Energy range used in the fit\n%energy\n limits = -14 8 eV\n inc = 0.1 eV ! < ei\n%end_energy\n\n# Mandatory\n%bands\n%end_bands\n\n# PDOS\n%dos\n type = l k resolved\n%end_dos\n\n# Fitting parameters\n%fit\n type = EK+PQK\n method = lmd\n f_tol = 1.0d-3\n p_tol = 5.0d-2\n ncyc_max = 1000\n %elfit ! ____ s ____ ____ p ____ ____ d ____ K_EHT\n Ge 1 3 5 0 2 4 6 0 9 10 11 0 12\n %end_elfit\n%end_fit\n\"\"\"\n return script\n\n @classmethod\n def writeBigBlocks(cls, blocks):\n script = makeCollectBlock(name='substrate', blocks=blocks[0])\n script += makeCollectBlock(name='tip', blocks=blocks[1])\n script += makeCollectBlock(name='junction', blocks=['substrate', 'tip'])\n\n return script\n\n\n def writeDefaults(self, atoms, mode):\n ei = mode.broadening()\n if len(atoms.regions()) == 0:\n stack_dim = 0\n else:\n stack_dim = 3\n\n return \"\"\"%defaults\nout_level = 0\"\"\" + \"\"\"\n stack_dim = %d\n rc = 50 A\n ei = %.3f eV\n ef = -12.15 eV\n kcut = 30 A\"\"\"%(stack_dim, ei) + \"\"\"\n%end_defaults\n\n\"\"\"\n\n @classmethod\n def writeScan(cls, mode, lattice):\n if isinstance(mode, Topographic):\n voltage = mode['voltage']\n current = float(mode['current'])/1000\n script = \"\"\"\n########################### scan ###########################\n%energy\"\"\" + \"\"\"\n bias = %.2f V\n inc = 0.01 eV\"\"\"%voltage + \"\"\"\n%end_energy\n\n%scan\n first_order = T\n mode = topographic\n i_unit = nAmp\"\"\" + \"\"\"\n ifix = %.3f\"\"\"%current\n\n script+= \"\"\"\n scan = lattice\n lattice = %s\n rgrid = 0.4 A\"\"\"%lattice\n script += \"\"\"\n%end_scan\n\n%current\n%end_current\n\"\"\"\n elif isinstance(mode, STSMode):\n mini, maxi, step = mode['mini'], mode['maxi'], mode['step']\n script = \"\"\"\n%energy\"\"\" + \"\"\"\n limits = %.2f %.2f eV\n e_fix = 0.0 eV Right\n inc = %.4f eV \"\"\" % (mini, maxi, step) + \"\"\"\n%end_energy\n\n%current\n type = e resolved\n%end_current\n\n\"\"\"\n\n\n else:\n raise Exception\n\n return script\n\n def basisSet(self):\n return self.get('basis_set', Green)\n\n def aseToStructure(self, atoms, EK_data=None):\n names = self.atomsNameList(atoms)\n return aseToGreen(atoms, names, EK_data=EK_data)\n\n def atomsNameList(self, atoms):\n element_basis_sets = self.basisSet()['element_basis_sets']\n species, species_identifiers = getSpecies(atoms, element_basis_sets)\n assert not 0 in species_identifiers\n names = np.array(['X'*100]*len(atoms))\n for key, basis_set in species.iteritems():\n mask = key == species_identifiers\n names[mask] = basis_set.identifier()\n\n return names\n\n def writeEHTHamiltonian(self, atoms):\n return scriptEHT(atoms, self.get('basis_set', Green)['element_basis_sets'])\n\n @classmethod\n def writeGraphic(cls, atoms, mode):\n pixels = (301, 301)\n size_x = max(atoms.cell[:, 0]) - min(atoms.cell[:, 0])\n size_y = max(atoms.cell[:, 1]) - min(atoms.cell[:, 1])\n dx = float(size_x)/pixels[0]\n dy = float(size_y)/pixels[1]\n start_x, end_x = (-(size_x - dx)/2, (size_x - dx)/2)\n start_y, end_y = (-(size_y - dy)/2, (size_y - dy)/2)\n if isinstance(mode, Topographic):\n script=\"\"\"%plot\n green_file = junction.Z\n type = grid\n x = pix\n y = pix\"\"\" + \"\"\"\n limits_x = %.5f %.5f %d\n limits_y = %.5f %.5f %d\n out_file = topography.dat\"\"\" % (start_x, end_x, pixels[0], start_y, end_y, pixels[1]) + \"\"\"\n%end_plot\n\"\"\"\n elif isinstance(mode, STSMode):\n script = \"\"\"%plot\n green_file = junction.TE\n type = table\n f = te\n x = e\n out_file = TE.table\n%end_plot\"\"\"\n\n return script\n\n","sub_path":"CalcTroll/Plugins/Programs/Green.py","file_name":"Green.py","file_ext":"py","file_size_in_byte":16131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"154790640","text":"# -*- coding: utf-8 -*-\n# Author:leali\n# Description: 序列化与反序列化,还可自定义对象进行处理,未完成\n# 通常方法如果不序列化可以采用str/eval进行处理\n# Version:v1.0\n# Date:4/13/2018-10:35 AM\nimport json\nimport pickle\nimport time\nimport random\nimport os\nimport shelve\n\nLENGTH = 1024 * 10240\n\n\ndef test_pickle():\n \"\"\"\n dumps 将数据通过特殊的形式转换为只有py语言识别的字符串\n loads 解析特殊字符串\n dump/load 转换/解析 操作文件\n 参数说明:对象持久化\n obj: 要持久化保存的对象;\n file: 一个拥有 write() 方法的对象,并且这个 write() 方法能接收一个字符串作为参数。\n 这个对象可以是一个以写模式打开的文件对象或者一个 StringIO 对象,或者其他自定义的满足条件的对象。\n protocol: 这是一个可选的参数,默认为 0 ,如果设置为 1 或 True,\n 则以高压缩的二进制格式保存持久化后的对象,否则以ASCII格式保存\n :return:\n \"\"\"\n data = {\"k1\": 123, \"k2\": \"hello\"}\n after = pickle.dumps(data)\n print(after)\n with open(\"data/pickle.pk\", 'wb') as file:\n # 转换并写入文件\n pickle.dump(data, file)\n\n with open(\"data/pickle.pk\", \"rb\") as file:\n res = pickle.load(file)\n print(res)\n\n\ndef test_cpickle():\n d = {}\n a = []\n for i in range(LENGTH):\n a.append(random.randint(0, 255))\n\n d[\"a\"] = a\n\n print(\"dumping...\")\n\n t1 = time.time()\n pickle.dump(d, open(\"data/tmp1.dat\", \"wb\"), True)\n print(\"pickle-dump-True: %.3fs\" % (time.time() - t1))\n\n t1 = time.time()\n pickle.dump(d, open(\"data/tmp2.dat\", \"wb\"))\n print(\"pickle-dump-False: %.3fs\" % (time.time() - t1))\n\n t1 = time.time()\n json.dump(d, open(\"data/tmp3.dat\", \"w\"))\n print(\"json-dump: %.3fs\" % (time.time() - t1))\n\n s1 = os.stat(\"tmp1.dat\").st_size\n s2 = os.stat(\"tmp2.dat\").st_size\n s3 = os.stat(\"tmp3.dat\").st_size\n\n print(\"%d, %d, %.2f%%\" % (s1, s2, 100.0 * s1 / s2))\n print(\"%d, %d, %.2f%%\" % (s1, s3, 100.0 * s1 / s3))\n\n print(\"loading...\")\n\n t1 = time.time()\n with open(\"data/tmp1.dat\", \"rb\") as obj1:\n pickle.load(obj1)\n print(\"pickle-load-True: %.3fs\" % (time.time() - t1))\n\n t1 = time.time()\n with open(\"data/tmp2.dat\", \"rb\") as obj2:\n pickle.load(obj2)\n print(\"pickle-load-False: %.3fs\" % (time.time() - t1))\n t1 = time.time()\n with open(\"data/tmp3.dat\", \"rb\") as obj3:\n json.load(obj3)\n print(\"json-load-True: %.3fs\" % (time.time() - t1))\n\n\nclass Person(object):\n def __init__(self):\n self.__name = \"LEAL\"\n self.__age = 25\n\n def __str__(self):\n return \"name: {}, age: {}\".format(self.__name, self.__age)\n\n\npath = \"data/shelve.txt\"\n\n\ndef shelve_write():\n \"\"\"\n 序列化\n :return:\n \"\"\"\n\n with shelve.open(path) as write: # 打开\n write[\"nums\"] = [1, 2, 3, 4, 5] # 写\n write[\"obj\"] = Person()\n\n\ndef shelve_read():\n \"\"\"\n 反序列化\n :return:\n \"\"\"\n with shelve.open(path) as read: # 打开\n nums = read.get(\"nums\") # 读取\n print(nums)\n clazz = read[\"obj\"]\n print(clazz)\n\n del read[\"obj\"] # 删除\n print(\"obj\" in read)\n\n keys = list(read.keys()) # 所有key\n print(keys)\n\n\ndef shelve_func():\n # 打开, filename:文件名, writeback:是否回写(True回写,耗内存), 返回Shelf对象\n # shelve.open(filename, flag='c', protocol=None, writeback=False)\n d = shelve.open(path)\n\n # Shelf\n # 支持字典支持的所有方法\n # get(self, key, default=None) // 获取 == data = shelf[\"key\"]\n data = d.get(\"key\")\n d.sync() # 同步(清空缓存,同步磁盘)\n d.close() # 同步并关闭\n\n # class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')\n # class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8') // Shelf的子类\n # class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False) // Shelf的子类\n\n\nif __name__ == \"__main__\":\n \"\"\"\n 性能比较:\n json,序列化和解析用时长,但压缩率为pickle的40%\n pickle,时间短\n 需要与外部系统交互时用json模块;\n 需要将少量、简单Python数据持久化到本地磁盘文件时可以考虑用pickle模块;\n 需要将大量Python数据持久化到本地磁盘文件或需要一些简单的类似数据库的增删改查功能时,可以考虑用shelve模块\n \"\"\"\n # test_pickle()\n # test_cpickle()\n shelve_write()\n shelve_read()\n","sub_path":"Study/oldboy/base/moudle_json.py","file_name":"moudle_json.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"33058205","text":"#!/usr/bin/env python\n\nfrom bson import json_util\nimport xml.etree.ElementTree as ET\nimport re\nfrom collections import defaultdict\nfrom pprint import pprint\nimport json\nimport datetime\n\ndef parse(osm_file):\n '''Parse the osm document and dump the data as json format.'''\n context = ET.iterparse(osm_file)\n with open('data_ny.json', 'w') as fp:\n for event, elem in context:\n node = shape_element(elem)\n if node is not None:\n json.dump(node, fp, default=json_util.default)\n\n\ndef update_street_name(name):\n '''Update street name to standardize street types. '''\n mapping = {\n \"\\s+St.$\": \" Street\",\n \"\\s+Rd.$\":\" Road\",\n \"\\s+Ave.$\":\" Avenue\",\n \"\\s+BLVD$\":\" Boulevard\",\n \"\\s+St$\": \" Street\",\n \"\\s+Rd$\":\" Road\",\n \"\\s+Ave$\":\" Avenue\",\n }\n for key, item in mapping.items():\n if re.search(key, name, re.IGNORECASE)!=None:\n insensitive = re.compile(key, re.IGNORECASE)\n return insensitive.sub(item, name)\n\n return name\n\ndef shape_element(element):\n '''Shape each element of way, node, or relation and return a dict.'''\n PROBLEM_CHARS = re.compile(r'[=\\+/&<>;\\'\"\\?%#$@\\,\\. \\t\\r\\n]')\n\n node = {}\n if element.tag == \"way\" or element.tag == \"node\" or element.tag==\"relation\":\n node[\"id\"] = element.attrib[\"id\"];\n\n #visible\n if element.get(\"visible\"):\n node[\"visible\"] = element.get(\"visible\");\n\n node[\"id\"] = element.attrib[\"id\"];\n node[\"type\"] = element.tag\n\n #position\n #Convert lat and lon to floating numbers\n lat = element.get(\"lat\", None)\n lon = element.get(\"lon\", None)\n if lat is not None and lon is not None:\n node[\"pos\"] = [float(lat),float(lon)]\n\n #created\n #convert timestamp to datetime object\n node[\"created\"] = {\n \"version\":element.attrib[\"version\"],\n \"changeset\":element.attrib[\"changeset\"],\n \"timestamp\":datetime.datetime.strptime(element.attrib[\"timestamp\"],\n \"%Y-%m-%dT%H:%M:%SZ\"),\n \"user\":element.attrib[\"user\"],\n \"uid\":element.attrib[\"uid\"]\n }\n\n tags = defaultdict(dict)\n for tag in element.iter('tag'):\n key = tag.attrib[\"k\"]\n value = tag.attrib[\"v\"]\n m = PROBLEM_CHARS.search(key)\n if m is None: # No problem\n if key.find(\":\")!=-1:\n #deal with multi-level keys\n key_items = key.split(\":\")\n\n if key_items[1]==\"street\" or key_items[1]==\"street_2\":\n value = update_street_name(value)\n\n temp = tags\n for key_item in key_items[0:-1]:\n item = temp.get(key_item,None)\n if item==None: #does not exists; create a new dictionary\n temp[key_item] = defaultdict(dict)\n elif type(item)!=type(defaultdict(dict)): #exists but wrong data type\n item_value = temp[key_item]\n temp[key_item] = defaultdict(dict)\n temp[key_item][key_item] = item_value\n #go to the next level\n temp = temp[key_item]\n #set the value of the lowest key item.\n temp[key_items[-1]] = value\n else:\n #convert height to floating numbers.\n if key == \"height\":\n tags[key] = extract_number(value)\n else:\n tags[key] = value\n\n #merge node dict.\n node.update(tags)\n\n #reference nodes\n refs = []\n for tag in element.iter('nd'):\n refs.append(tag.attrib[\"ref\"])\n if len(refs)>0:\n node[\"node_refs\"] = refs\n\n #members for relations\n members = []\n for tag in element.iter('member'):\n members.append(\n {\"member\":\n {\"type\":tag.attrib[\"type\"],\n \"ref\":tag.attrib[\"ref\"],\n \"role\":tag.attrib[\"role\"]}\n }\n )\n\n if len(members)>0:\n node[\"members\"] = members\n\n return node\n else:\n return None\n\ndef extract_number(s):\n '''Extract a floating point number for a string.'''\n num = re.compile(\"[0-9]*\\.?[0-9]*\")\n m = num.search(s)\n return float(m.group())\n\nif __name__ == \"__main__\":\n OSM_FILE = \"brooklyn_new-york.osm\"\n parse(OSM_FILE)\n","sub_path":"munging.py","file_name":"munging.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"386738578","text":"from random import randint\n\nclass Character:\n def __init__(self, name):\n self.weps = {}\n self.spells = {}\n self.items = {'health potion':2}\n self.gold = 0\n self.p_name = name\n\nclass Rogue(Character):\n name = 'rogue'\n max_hp = 6\n speed = 3\n stealth = 2\n\n def __init__(self, option, name):\n Character.__init__(self, name)\n self.hp = 6\n self.ac = 0\n if option == 1:\n self.choice_1()\n elif option == 2:\n self.choice_2()\n\n def choice_1(self):\n self.weps['knives'] = 2\n self.items['health potion'] += 1\n\n def choice_2(self):\n self.weps['knives'] = 2\n self.items['shawl of silence'] = 1\n self.stealth += 1\n\nclass Mage(Character):\n name = 'mage'\n max_hp = 8\n speed = 2\n stealth = 1\n\n def __init__(self, option, name):\n Character.__init__(self, name)\n self.hp = 8\n self.ac = 1\n if option == 1:\n self.choice_1()\n elif option == 2:\n self.choice_2()\n\n def choice_1(self):\n self.spells['super spell'] = 3\n self.items['health potion'] += 1\n\n def choice_2(self):\n self.spells['attack spell'] = 2\n self.spells['healing spell'] = 4\n\nclass Warrior(Character):\n name = 'warrior'\n max_hp = 10\n speed = 1\n stealth = 0\n\n def __init__(self, option, name):\n Character.__init__(self, name)\n self.hp = 10\n self.ac = 2\n if option == 1:\n self.choice_1()\n elif option == 2:\n self.choice_2()\n\n def choice_1(self):\n self.weps['big sword'] = 5\n\n def choice_2(self):\n self.weps['broad sword'] = 3\n self.items['sheild'] = 1\n self.ac += 1\n\nclass Enemy:\n def __init__(self):\n _types = ['Gnome', 'Orc', 'Goblin', 'Rat', 'Skellington']\n _weps = ['Knife', 'Sword', 'Stick', 'Pie']\n self.hp = randint(5,10)\n self.name = _types[randint(0,4)]\n self.wep = _weps[randint(0,3)]\n self.dam = randint(2,4)\n\ndef room(num_oppo, opponents):\n print('\\nIn the room, there is:')\n intros = ['- A spoopy {0} with a {1}', '- Followed by a {0} holding a {1}', '- With his friend the {0} carrying a {1}']\n _enemy_iter = 0\n for number in range(0,len(opponents)):\n print(intros[_enemy_iter].format(opponents[_enemy_iter].name,opponents[_enemy_iter].wep))\n _enemy_iter += 1\n\ndef attack(player, numbered_opponents):\n _condition = False\n while _condition == False:\n print('What fight with bruh')\n weapon = str(input('- '))\n weapon = weapon.lower()\n if weapon in ['exit', 'cancel', 'stop']:\n return None, None\n\n if weapon in player.weps:\n damage = player.weps[weapon]\n _condition = True\n\n _condition = False\n while _condition == False:\n print('Who you attacking.')\n for key, val in sorted(numbered_opponents.items()):\n print(key ,':', val.name, '( HP:',val.hp,'Damage:',val.dam,')')\n\n try:\n opponent = int(input('- '))\n\n except ValueError:\n print('Try again')\n\n if opponent in numbered_opponents:\n print('The',numbered_opponents[opponent].name,'took',damage,'damage.')\n _condition = True\n\n return damage, opponent\n\n _condition = False\n print('Your spells are:')\n for spell, damage in player.spells:\n if spell == 'healing spell':\n print('- Healing spell ( fuck yeah )')\n\n else:\n print('- {0} ( does {1} damage)'.format(spell, damage))\n\n print('')\n while _condition == False:\n print('What spell:')\n spell = str(input('- '))\n if spell in player.spells:\n damage = player.spells[spell]\n\n elif spell == 'none' or spell == 'exit' or spell == 'stop':\n return None, None\n\n while _condition == False:\n print('Who you attacken')\n target = str(input('- '))\n if target in numbered_opponents:\n print('{0} took {1} damage.'.format(target.title(), damage))\n\n return damage, target\n\ndef spell(player, numbered_opponents):\n _condition = False\n while _condition == False:\n print('What spell bruh: ')\n spell = str(input('- '))\n if spell.lower() in player.spells:\n damage = player.spells[spell]\n print('\\nWho you attacken bruh?')\n for key, val in sorted(numbered_opponents.items()):\n print(key ,':', val.name, '( HP:',val.hp,'Damage:',val.dam,')')\n\n target = int(input('- '))\n if target in ['exit','stop','quit','cancel']:\n return None, None\n\n if target in numbered_opponents:\n print('{0} took {1} damage.'.format(numbered_opponents[target].name, damage))\n return damage, target\n\n\n#\n# END OF FUNCTION DEFINITIONS\n#\n# COMMENCING SCRIPT\n#\n\n\nprint('How many players? (1 - 3)')\nnum_players = int(input('- '))\nplayers = []\ndead_players = []\nclasses = {'mage':Mage,'rogue':Rogue,'warrior':Warrior}\noptions = {'warrior':'1: One big sword ( 5 damage )or \\n2: One sword and sheild ( 3 damage, +1 AC)','mage':'1: One super damage spell ( 3 ) + health potion \\n2: One regular damage spell ( 2 damage ) + 1 healing spell','rogue':'1: Knives + health potion \\n2: Knives + better cloak'}\nfor player in range(1,num_players+1):\n print('READY PLAYER',player)\n name = str(input('Name: '))\n print('Choose a class: ')\n print(' Warrior: 10 HP, 2 AC, 0 stealth, 1 speed')\n print(' Mage: 8 HP, 1 AC, 1 stealth, 2 speed')\n print(' Rogue: 6 hp, 0 AC, 2 stealth, 3 speed\\n')\n player_class = str(input('- '))\n if player_class.lower() in classes:\n print(options[player_class.lower()])\n option = int(input('- '))\n new_player = classes[player_class.lower()](option, name)\n players.append(new_player)\n\nwhile bool(players) == True:\n first_run = True\n enemies = randint(1,3) # Chooses how many enemies to create\n loot = randint(10, 50)\n num_oppo = enemies\n opponents = [] # We add each new enemy to this because we don't know how many enemeis we'll have\n enemy_1 = Enemy() # Makes the first enemy\n opponents.append(enemy_1) # Adds it to the list\n enemies -= 1 # takes off one to create\n if enemies >= 1:\n enemy_2 = Enemy()\n opponents.append(enemy_2)\n enemies -= 1\n if enemies >= 0:\n enemy_3 = Enemy()\n opponents.append(enemy_3)\n\n room(num_oppo, opponents)\n numbered_opponents = {}\n key_num = 1\n for _enemy in opponents:\n numbered_opponents[key_num] = _enemy\n key_num += 1\n\n \"\"\"\n ### Enemy data structures\n ### opponents: LIST of Enemy() instances, for\n ### num_oppo: INT of how many instances there are, for\n ### numbered_opponents: DICT of instnaces, with number keys to each instance, for\n \"\"\"\n\n _ = input('\\nPress any key to continue')\n\n while bool(numbered_opponents) == True:\n for player_1 in players:\n print('\\nYour turn',player_1.p_name)\n actions = player_1.speed\n if first_run == True:\n actions += player_1.stealth\n first_run = False\n\n while actions > 0:\n print('')\n print('You got',actions,'actions left')\n print('What you do:')\n print(' i: inventory \\n a: attack \\n h: use a health potion \\n s: cast a spell \\n e: end turn')\n choice = str(input('- '))\n if choice.lower() == 'i':\n print(\"Items:\",player_1.items,'\\nWeapons:',str(player_1.weps), '\\nSpells',str(player_1.spells))\n\n elif choice == 'e':\n actions = 0\n\n\n elif choice.lower() in ['s','a']:\n if choice.lower() == 's':\n damage, target = spell(player_1, numbered_opponents)\n\n if choice.lower() == 'a':\n damage, target = attack(player_1, numbered_opponents)\n\n if (damage and target) == None:\n pass\n\n else:\n numbered_opponents[target].hp -= damage\n actions -= 1\n if numbered_opponents[target].hp < 1:\n print('\\nThe',numbered_opponents[target].name,'died. \\n')\n del numbered_opponents[target]\n\n elif choice.lower() == 'h':\n print('\\nYou used a health potion to heal. \\n')\n player_1.hp = player_1.max_hp\n print('You have',player_1.hp,'health points left. \\n')\n actions -= 1\n\n _ = input('Press any key to continue.')\n\n if bool(numbered_opponents) == False:\n print('The room is quiet. \\n')\n print('In the rubble you each find',loot,'pieces of gold.')\n for player in players:\n player.gold += loot\n\n _ = input('\\nPress any key to continue')\n\n else:\n iter_val = 1\n for key, _enemy in numbered_opponents.items():\n if _enemy.dam - player_1.ac <= 0:\n print('\\nThe', _enemy.name + \"'s attack was uneffective and did no damage.\")\n\n else:\n print('\\nThe', _enemy.name, 'does', _enemy.dam - player_1.ac, 'damage.')\n player_1.hp = player_1.hp - (_enemy.dam - player_1.ac)\n\n iter_val += 1\n print('You now have',player_1.hp,'health left \\n')\n\n _ = input('Press any key to continue.')\n\n if player_1.hp <= 0:\n print('Shit son, you dead.')\n dead_players.append(player_1)\n players.remove(player_1)\n numbered_opponents = []\n\nprint('>>> GAME OVER <<< \\n')\nfor player in dead_players:\n print('Well done',player.p_name +'. You got', player.gold,'gold. Well done. \\n')\n _ = input('Hit return to finish')\n","sub_path":"game_new.py","file_name":"game_new.py","file_ext":"py","file_size_in_byte":10279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"217735797","text":"from random import seed\r\nfrom random import uniform\r\nfrom random import randrange\r\nfrom random import random\r\nfrom csv import reader\r\nfrom math import exp\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import cohen_kappa_score\r\nimport numpy as np\r\nimport csv\r\nfrom decimal import Decimal\r\n\r\n \r\n# Load a CSV file\r\ndef loadCsv(filename):\r\n trainSet = []\r\n \r\n lines = csv.reader(open(filename, 'r'))\r\n dataset = list(lines)\r\n for i in range(len(dataset)):\r\n for j in range(4):\r\n #print(\"DATA {}\".format(dataset[i]))\r\n dataset[i][j] = float(dataset[i][j])\r\n trainSet.append(dataset[i])\r\n return trainSet\r\n \r\n# Convert string column to float\r\ndef str_column_to_float(dataset, column):\r\n for row in dataset:\r\n try:\r\n row[column] = float(row[column])\r\n except ValueError:\r\n print(\"Error with row\",column,\":\",row[column])\r\n pass\r\n \r\n# Convert string column to integer\r\ndef str_column_to_int(dataset, column):\r\n class_values = [row[column] for row in dataset]\r\n unique = set(class_values)\r\n \r\n lookup = dict()\r\n for i, value in enumerate(unique):\r\n lookup[value] = i+1\r\n for row in dataset:\r\n row[column] = lookup[row[column]]\r\n print(lookup)\r\n return lookup\r\n \r\n# Find the min and max values for each column\r\ndef dataset_minmax(dataset):\r\n minmax = list()\r\n stats = [[min(column), max(column)] for column in zip(*dataset)]\r\n return stats\r\n \r\n# Rescale dataset columns to the range 0-1\r\ndef normalize_dataset(dataset, minmax):\r\n for row in dataset:\r\n for i in range(len(row)-1):\r\n row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0])\r\n \r\ndef splitData(dataset, sRatio):\r\n trainSet = []\r\n copy = list(dataset)\r\n trainSize = int(len(dataset) * sRatio) \r\n seed(8)\r\n while len(trainSet) < trainSize: \r\n index = randrange(len(copy)) \r\n trainSet.append(copy.pop(index))\r\n return [trainSet, copy]\r\n \r\n# Calculate accuracy percentage\r\ndef accuracy_metric(actual, predicted):\r\n correct = 0\r\n for i in range(len(actual)):\r\n if actual[i] == predicted[i]:\r\n correct += 1\r\n return correct / float(len(actual)) * 100.0\r\n \r\n# Evaluate an algorithm using a cross validation split\r\ndef evaluate_algorithm(train_set, test_set, algorithm, *args):\r\n #print(test_set)\r\n predicted = algorithm(train_set, test_set, *args)\r\n #print(predicted)\r\n actual = [int(row[-1]) for row in test_set]\r\n #print(actual)\r\n accuracy = accuracy_metric(actual, predicted)\r\n cm = confusion_matrix(actual, predicted)\r\n print('\\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in cm]))\r\n #confusionmatrix = np.matrix(cm)\r\n FP = cm.sum(axis=0) - np.diag(cm)\r\n FN = cm.sum(axis=1) - np.diag(cm)\r\n TP = np.diag(cm)\r\n TN = cm.sum() - (FP + FN + TP)\r\n print('False Positives\\n {}'.format(FP))\r\n print('False Negetives\\n {}'.format(FN))\r\n print('True Positives\\n {}'.format(TP))\r\n print('True Negetives\\n {}'.format(TN))\r\n TPR = TP/(TP+FN)\r\n print('Sensitivity \\n {}'.format(TPR))\r\n TNR = TN/(TN+FP)\r\n print('Specificity \\n {}'.format(TNR))\r\n Precision = TP/(TP+FP)\r\n print('Precision \\n {}'.format(Precision))\r\n Recall = TP/(TP+FN)\r\n print('Recall \\n {}'.format(Recall))\r\n Acc = (TP+TN)/(TP+TN+FP+FN)\r\n print('Áccuracy \\n{}'.format(Acc))\r\n Fscore = 2*(Precision*Recall)/(Precision+Recall)\r\n print('FScore \\n{}'.format(Fscore))\r\n k=cohen_kappa_score(actual, predicted)\r\n print('Çohen Kappa \\n{}'.format(k))\r\n \r\n \r\n \r\n# Calculate neuron activation for an input\r\ndef activate(weights, inputs):\r\n activation = weights[-1]\r\n for i in range(len(weights)-1):\r\n activation += weights[i] * inputs[i]\r\n return activation\r\n \r\n# Transfer neuron activation\r\ndef transfer(act):\r\n val = 0.5\r\n y = 1.0 / (1.0 + (0.91 * (pow(act,val)*pow(1-act,1-val))))\r\n y = abs(y)\r\n return y\r\n \r\n# Forward propagate input to a network output\r\ndef forward_propagate(network, row):\r\n inputs = row\r\n for layer in network:\r\n new_inputs = []\r\n for neuron in layer:\r\n activation = activate(neuron['weights'], inputs) \r\n #print(\"weight {}\".format(neuron['weights']))\r\n #print(\"x {}\".format(activation))\r\n neuron['input'] = activation\r\n neuron['output'] = transfer(activation)\r\n #print(\" y {}\".format(neuron['output']))\r\n new_inputs.append(neuron['output'])\r\n #new_inputs.append(neuron['input'])\r\n inputs = new_inputs\r\n return inputs\r\n \r\n# Calculate the derivative of an neuron output\r\ndef transfer_derivative(output, inp):\r\n derv = output * (1.0 - output)/ (inp * ( 1.0 - inp ))\r\n derv = derv * (inp - 0.5)\r\n return derv\r\n \r\n# Backpropagate error and store in neurons\r\ndef backward_propagate_error(network, expected):\r\n for i in reversed(range(len(network))):\r\n layer = network[i]\r\n errors = list()\r\n if i != len(network)-1:\r\n for j in range(len(layer)):\r\n error = 0.0\r\n for neuron in network[i + 1]:\r\n error += (neuron['weights'][j] * neuron['delta'])\r\n errors.append(error)\r\n else:\r\n for j in range(len(layer)):\r\n neuron = layer[j]\r\n errors.append(expected[j] - neuron['output'])\r\n for j in range(len(layer)):\r\n neuron = layer[j]\r\n neuron['delta'] = errors[j] * transfer_derivative(neuron['output'], neuron['input'])\r\n \r\n# Update network weights with error\r\ndef update_weights(network, row, l_rate):\r\n for i in range(len(network)):\r\n inputs = row[:-1]\r\n \r\n if i != 0:\r\n inputs = [neuron['output'] for neuron in network[i - 1]]\r\n for neuron in network[i]:\r\n for j in range(len(inputs)):\r\n temp = l_rate * neuron['delta'] * inputs[j] + mu * neuron['prev'][j] \r\n neuron['weights'][j] += temp\r\n #print(\"neuron weight{} \\n\".format(neuron['weights'][j]))\r\n neuron['prev'][j] = temp\r\n temp = l_rate * neuron['delta'] + mu * neuron['prev'][-1]\r\n neuron['weights'][-1] += temp\r\n neuron['prev'][-1] = temp\r\n #print(\"neuron {}\".format(neuron['weights']))\r\n \r\n \r\n# Train a network for a fixed number of epochs\r\ndef train_network(network, train, l_rate, n_epoch, n_outputs):\r\n for epoch in range(n_epoch):\r\n for row in train:\r\n outputs = forward_propagate(network, row)\r\n #print(network)\r\n expected = [0 for i in range(n_outputs)]\r\n expected[int(row[-1])] = 1\r\n #print(\"expected row{}\\n\".format(expected))\r\n backward_propagate_error(network, expected)\r\n update_weights(network, row, l_rate)\r\n \r\n# Initialize a network\r\ndef initialize_network(n_inputs, n_hidden, n_outputs):\r\n network = list()\r\n hidden_layer = [{'weights':[round(uniform(0.00,0.1),4) for i in range(n_inputs + 1)], 'prev':[0 for i in range(n_inputs+1)]} for i in range(n_hidden)] \r\n network.append(hidden_layer)\r\n #hidden_layer = [{'weights':[random() for i in range(n_hidden + 1)], 'prev':[0 for i in range(n_hidden+1)]} for i in range(n_hidden)]\r\n #network.append(hidden_layer)\r\n output_layer = [{'weights':[round(uniform(0.0,0.1),4) for i in range(n_hidden + 1)],'prev':[0 for i in range(n_hidden+1)]} for i in range(n_outputs)]\r\n network.append(output_layer)\r\n print(network)\r\n return network\r\n \r\n# Make a prediction with a network\r\ndef predict(network, row):\r\n outputs = forward_propagate(network, row)\r\n #print(outputs)\r\n value = outputs.index(max(outputs))\r\n return value\r\n \r\n# Backpropagation Algorithm With Stochastic Gradient Descent\r\ndef back_propagation(train, test, l_rate, n_epoch, n_hidden):\r\n n_inputs = len(train[0]) - 1\r\n n_outputs = len(set([row[-1] for row in train]))\r\n #print(\"output {}\".format(n_outputs))\r\n network = initialize_network(n_inputs, n_hidden, n_outputs)\r\n train_network(network, train, l_rate, n_epoch, n_outputs)\r\n #print(\"network {}\\n\".format(network))\r\n predictions = list()\r\n for row in test:\r\n prediction = predict(network, row)\r\n predictions.append(prediction)\r\n return(predictions)\r\n \r\n# Test Backprop on Seeds dataset\r\nseed(8)\r\n# load and prepare data\r\nfilename = 'dataset-rocky-all-feats-run.csv'\r\ndataset = loadCsv(filename)\r\nfor i in range(len(dataset[0])-1):\r\n str_column_to_float(dataset, i)\r\n# convert class column to integers\r\n#str_column_to_int(dataset, len(dataset[0])-1)\r\n# normalize input variables\r\n\r\nminmax = dataset_minmax(dataset)\r\nnormalize_dataset(dataset, minmax)\r\n# evaluate algorithm\r\nsRatio = 0.80\r\ntrainingSet, testSet = splitData(dataset, sRatio)\r\nl_rate = 0.04\r\nmu=0.01\r\nprint(\"learning rate, momentum\",l_rate,mu)\r\nmu=0.01\r\nn_epoch = 300\r\nn_hidden = 12\r\nevaluate_algorithm(trainingSet,testSet, back_propagation, l_rate, n_epoch, n_hidden)\r\n","sub_path":"SBAF_all_feat.py","file_name":"SBAF_all_feat.py","file_ext":"py","file_size_in_byte":10638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"29427793","text":"import random\nimport numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport tensorflow as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'\n\n\ndef reshape_to_category_feature(x, category_count=2):\n return tf.one_hot(x, depth=category_count)\n\n\ndef reshape_input(cat1, cat2):\n return {\n 'cat1': reshape_to_category_feature(cat1),\n 'cat2': reshape_to_category_feature(cat2),\n }\n\n\ndef build_labels(cat1, cat2):\n return reshape_to_category_feature(list(int(c1 + c2 > 0) for c1, c2 in zip(cat1, cat2)))\n\n\ndef init_model(optimizer):\n cat1_input = tf.keras.Input(shape=(2,), name=\"cat1\")\n cat2_input = tf.keras.Input(shape=(2,), name=\"cat2\")\n concated_layer = tf.keras.layers.concatenate([cat1_input, cat2_input])\n target_layer = tf.keras.layers.Dense(2, name=\"target\")(concated_layer)\n\n model = tf.keras.Model(\n inputs=[cat1_input, cat2_input],\n outputs=target_layer,\n )\n\n tf.keras.utils.plot_model(model, \"multi_input_and_output_model.png\", show_shapes=True)\n\n model.compile(optimizer=optimizer,\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy'])\n print(model.summary())\n return model\n\n\ndef binary_or(train_size, epochs_count, optimizer='adam', batch_size=1):\n model = init_model(optimizer)\n\n train_cat1 = list(random.randint(0, 1) for i in range(train_size))\n train_cat2 = list(random.randint(0, 1) for i in range(train_size))\n train_labels = build_labels(train_cat1, train_cat2)\n\n test_cat1 = [0, 1, 1, 0]\n test_cat2 = [0, 1, 0, 1]\n test_labels = build_labels(test_cat1, test_cat2)\n\n input_data = reshape_input(train_cat1, train_cat2)\n model.fit(\n input_data,\n {\n 'target': train_labels,\n },\n epochs=epochs_count,\n batch_size=batch_size\n )\n m = model.evaluate(reshape_input(test_cat1, test_cat2), {\"target\": test_labels})\n print(m)\n return m[1]\n\n\naccuracy = binary_or(100, 30)\nassert accuracy == 1.0\n\n","sub_path":"tools/predict_office/scripts/tensorflow_examples/two_categories.py","file_name":"two_categories.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"254504249","text":"#python\n\n\"\"\" \n\tSelect By Weight script 1.0 by Richard Rodriguez (gm770)\n\t- Tested on Modo 501 and 401sp5 for PC\n\t\n\tHow to use:\n\t- Run with no Edges selected, it will select all weighted edges\n\t- Run with Edges selected, it will select all edges that have \n\tthe same weight as any of the selected edges\n\"\"\"\n\nimport lx\n\n\nmain=lx.eval(\"query layerservice layers ? main\")\nedge_cnt = lx.eval(\"query layerservice edge.N ? all\")\nif edge_cnt != 0:\n\tedge_list = []\n\tweight_list = []\n\n\tfor x in range(edge_cnt):\n\t\tw = lx.eval(\"query layerservice edge.creaseWeight ? %s\" % x)\n\t\ts = lx.eval(\"query layerservice edge.selected ? %s\" % x)\n\t\tif s == 1 and w not in weight_list:\n\t\t\tweight_list.append(w)\n\t\ta,b = lx.eval(\"query layerservice edge.vertList ? %s\" % x)\n\t\tedge = {\"i\":x, \"w\":w, \"a\":a, \"b\":b}\n\t\tedge_list.append(edge)\n\n\twl_cnt = len(weight_list)\n\tlx.eval(\"select.drop edge\")\n\tif wl_cnt != 0:\n\t\tfor edge in edge_list: \n\t\t\tif edge['w'] in weight_list:\n\t\t\t\tlx.eval(\"select.element %s edge add %s %s\" % (main, edge['a'], edge['b']) )\n\telse:\n\t\tfor edge in edge_list:\n\t\t\tif edge['w'] != 0:\n\t\t\t\tlx.eval(\"select.element %s edge add %s %s\" % (main, edge['a'], edge['b']) )\t","sub_path":"Scripts/eterea_weightTools/scripts/selectByWeight.py","file_name":"selectByWeight.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619948002","text":"# -*- coding: utf-8 -*-\nfrom camper import BaseForm, db, BaseHandler, logged_in, ensure_barcamp, is_admin\nfrom .base import BarcampBaseHandler\nfrom camper.db.barcamp import WorkflowError\nfrom starflyer import redirect\n\nclass Permissions(BarcampBaseHandler):\n \"\"\"screen for private/public and admin management\"\"\"\n\n template = \"barcamp/permissions.html\"\n\n @ensure_barcamp()\n @logged_in()\n @is_admin()\n def get(self, slug = None):\n \"\"\"render the view\"\"\"\n return self.render(\n title = self.barcamp.name,\n **self.barcamp)\n\n @ensure_barcamp()\n @logged_in()\n @is_admin()\n def post(self, slug = None):\n \"\"\"set the workflow state for the barcamp\"\"\"\n try:\n self.barcamp.set_workflow(self.request.form.get(\"wf\",\"\"))\n self.barcamp.save()\n except WorkflowError:\n self.flash(self._(\"you cannot perform this action.\"), category=\"error\")\n if self.last_url:\n url = self.last_url\n else:\n url = self.url_for(\"barcamp\", slug=slug)\n return redirect(url)\n\n\nclass Admin(BarcampBaseHandler):\n \"\"\"add a new administrator.\n \"\"\"\n\n template = \"barcamp/permissions.html\"\n\n @ensure_barcamp()\n @logged_in()\n @is_admin()\n def post(self, slug = None):\n \"\"\"set the visibility of the barcamp\"\"\"\n email = self.request.form.get(\"email\")\n user = self.app.module_map.userbase.get_user_by_email(email)\n if user is None:\n self.flash(\"Ein Benutzer mit dieser E-Mail-Adresse wurde leider nicht gefunden.\", category=\"error\")\n return redirect(self.url_for(\"barcamp_permissions\", slug = slug))\n\n uid = str(user._id)\n if uid not in self.barcamp.admins:\n self.barcamp.add_admin(user)\n self.barcamp.save()\n self.flash(u\"%s ist nun ebenfalls ein Admin für dieses Barcamp.\" %user.fullname)\n\n return redirect(self.url_for(\"barcamp_permissions\", slug = slug))\n\n @ensure_barcamp()\n @logged_in()\n @is_admin()\n def delete(self, slug = None):\n uid = self.request.args.get(\"uid\")\n if uid == self.barcamp.created_by:\n self.flash(u\"Dem Ersteller des Barcamps kann das Admin-Recht nicht entzogen werden.\", category=\"error\")\n return redirect(self.url_for(\"barcamp_permissions\", slug = slug))\n if len(self.barcamp.admins)<2:\n self.flash(u\"Es muss mindestens einen Administrator geben.\", category=\"error\")\n return redirect(self.url_for(\"barcamp_permissions\", slug = slug))\n if uid in self.barcamp.admins:\n self.barcamp.remove_admin_by_id(uid)\n self.barcamp.save()\n self.flash(u\"Administrator gelöscht.\")\n return redirect(self.url_for(\"barcamp_permissions\", slug = slug))\n","sub_path":"camper/handlers/barcamp/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"520345449","text":"# coding=utf-8\nimport wx\nimport requests\nimport threading\nimport os\nfrom urllib.request import urlretrieve\nimport urllib\n# from urllib import parse\nfrom openpyxl import load_workbook\nimport time\n# import pandas as pd\nfrom bs4 import BeautifulSoup\nimport re\nimport socket\nimport datetime\n\n# 设置超时时间为30s\nsocket.setdefaulttimeout(30)\n\nAPP_TITLE = u'下载文件工具'\nAPP_ICON = 'res/python.ico'\n\n\nclass mainFrame(wx.Frame):\n\n def __init__(self, parent):\n wx.Frame.__init__(self, parent, -1, APP_TITLE)\n self.SetBackgroundColour(wx.Colour(255, 255, 255))\n self.SetSize((460, 420))\n self.Center()\n\n self.selectExcelPathBtn = wx.Button(self, -1, u'选择文件夹', pos=(10, 20), size=(100, -1), style=wx.ALIGN_LEFT)\n\n # wx.StaticText(self, -1, u'请求地址:', pos=(10, 20), size=(60, -1), style=wx.ALIGN_LEFT)\n self.excelFile = wx.TextCtrl(self, -1, '', pos=(130, 20), size=(260, -1), name='excelFile', style=wx.TE_LEFT)\n\n # self.selectOutPathBtn = wx.Button(self, -1, u'下载文件路径', pos=(10, 50), size=(100, -1), style=wx.ALIGN_LEFT)\n # self.outPath = wx.TextCtrl(self, -1, '', pos=(130, 50), size=(260, -1), name='outPath', style=wx.TE_LEFT)\n\n wx.StaticText(self, -1, u'Cookie:', pos=(10, 50), size=(60, -1), style=wx.ALIGN_LEFT)\n self.cookie = wx.TextCtrl(self, -1, 'SESSION=bd5f9323-30a0-481d-98ad-18697fdd3f24', pos=(130, 50),\n size=(260, -1), name='Cookie', style=wx.TE_LEFT)\n\n wx.StaticText(self, -1, u'下载时段:', pos=(10, 80), size=(60, -1), style=wx.ALIGN_LEFT)\n self.startHour = wx.TextCtrl(self, -1, '20', pos=(130, 80), size=(40, -1), name='开始时', style=wx.TE_LEFT)\n self.endHour = wx.TextCtrl(self, -1, '8', pos=(180, 80), size=(40, -1), name='结束时', style=wx.TE_LEFT)\n\n\n self.btn_start = wx.Button(self, -1, u'开始下载', pos=(10, 130), size=(80, -1))\n\n self.area = wx.TextCtrl(self, -1, '', pos=(10, 170), size=(380, 200), name='area',\n style=wx.TE_LEFT | wx.TE_MULTILINE)\n\n self.Bind(wx.EVT_BUTTON, self.OnSelectExcel, self.selectExcelPathBtn)\n # self.Bind(wx.EVT_BUTTON, self.OnSelectOutPath, self.selectOutPathBtn)\n self.btn_start.Bind(wx.EVT_LEFT_DOWN, self.startWork)\n\n # 设置是否暂停\n self.pause = False\n\n def OnSelectExcel(self, event):\n dlg = wx.DirDialog(self, u\"选择文件夹\", style=wx.DD_DEFAULT_STYLE)\n if dlg.ShowModal() == wx.ID_OK:\n print(dlg.GetPath()) # 文件夹路径\n self.excelFile.SetLabelText(dlg.GetPath())\n dlg.Destroy()\n\n # def OnSelectOutPath(self, event):\n # dlg = wx.DirDialog(self, u\"选择文件夹\", style=wx.DD_DEFAULT_STYLE)\n # if dlg.ShowModal() == wx.ID_OK:\n # print(dlg.GetPath()) # 文件夹路径\n # self.outPath.SetLabelText(dlg.GetPath())\n # dlg.Destroy()\n\n def startWork(self, event):\n if self.excelFile.GetValue() == '':\n self.area.AppendText(\"请选择Excel文件\\n\")\n return\n if self.cookie.GetValue() == '':\n self.area.AppendText(\"请输入cookie\\n\")\n return\n # if self.year.GetValue() == '':\n # self.area.AppendText(\"请输入年份\\n\")\n return\n\n t1 = threading.Thread(target=self.pre_work)\n t1.start()\n t2 = threading.Thread(target=self.keep_alive)\n t2.setDaemon(True)\n t2.start()\n\n def pre_work(self):\n\n if self.timeInDate() == False:\n self.pause = True\n\n self.excelFile.Disable()\n self.selectExcelPathBtn.Disable()\n # self.outPath.Disable()\n self.cookie.Disable()\n self.btn_start.Disable()\n # self.year.Disable()\n self.area.AppendText(\"开始查找Excel文件\\n\")\n fileDict = self.find_excel()\n if len(fileDict.items()) <= 0:\n self.area.AppendText(\"未找到Excel文件\\n\")\n self.excelFile.Enable()\n self.cookie.Enable()\n self.btn_start.Enable()\n self.selectExcelPathBtn.Enable()\n return\n\n for file, year in fileDict.items():\n self.area.Clear()\n self.area.AppendText(\"开始加载:\" + file + \"\\n\")\n ent_list = self.read_excel(file)\n t1 = time.time()\n size = len(ent_list)\n if size <= 0:\n self.area.AppendText(\"加载企业失败,结束下载\\n\")\n continue\n\n self.area.AppendText(\"加载完毕,开始下载文件\\n\")\n for r in range(0, size):\n while True:\n if self.pause == False:\n break\n else:\n self.area.AppendText(\"当前时间未在指定时间段内,等待中...\\n\")\n time.sleep(30)\n\n entInfo = ent_list[r]\n ent_name = entInfo.get(\"entName\")\n hangye = entInfo.get(\"hangye\")\n print(ent_name)\n if os.path.exists(os.path.join(self.excelFile.GetValue(), year, hangye)) == False:\n os.makedirs(os.path.join(self.excelFile.GetValue(), year, hangye))\n self.download(ent_name, hangye, year)\n time.sleep(0.3)\n t2 = time.time()\n t3 = int(t2) - int(t1)\n self.area.AppendText(\"下载耗时秒:\" + str(t3) + \"\\n\")\n\n self.area.AppendText(\"全部下载结束\\n\")\n self.excelFile.Enable()\n # self.outPath.Enable()\n self.cookie.Enable()\n self.btn_start.Enable()\n self.selectExcelPathBtn.Enable()\n # self.year.Enable()\n\n def keep_alive(self):\n print(\"刷新系统保持活跃\")\n header = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Referer': 'http://10.100.248.214/manager/reportInfo/list?hasReport=false',\n 'x-requested-with': 'XMLHttpRequest',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Accept-Encoding': 'gzip, deflate',\n 'Host': '10.100.248.214',\n 'Origin': 'http://10.100.248.214',\n 'Pragma': 'no-cache',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',\n 'Cookie': self.cookie.GetValue()\n }\n while True:\n if self.timeInDate() == False:\n self.pause = True\n # 调用系统接口,保持session活跃\n ret = requests.get('http://10.100.248.214/manager/index', timeout=10, headers=header)\n time.sleep(30)\n\n def timeInDate(self):\n curtHour = datetime.datetime.now().hour\n starthour = self.startHour.GetValue()\n endhour = self.endHour.GetValue()\n if starthour != \"\" and endhour != \"\":\n sh = int(starthour)\n eh = int(endhour)\n if eh < sh and curtHour>=sh and curtHour<24:\n return True\n if eh > sh and curtHour>=sh and curtHour 2:\n self.area.AppendText(\"找到文件:\" + file + \"\\n\")\n dict[file] = fileInfoArr[2] # os.path.join(self.excelFile.GetValue(), file)\n # 创建年份文件夹\n if os.path.exists(self.excelFile.GetValue() + \"\\\\\" + fileInfoArr[2]) == False:\n os.makedirs(self.excelFile.GetValue() + \"\\\\\" + fileInfoArr[2])\n return dict\n\n def read_excel(self, file):\n ent_list = []\n print('excel:', os.path.join(self.excelFile.GetValue(), file))\n wb = load_workbook(os.path.join(self.excelFile.GetValue(), file))\n sheet = wb.active\n rnum = sheet.max_row + 1\n cnum = sheet.max_column\n for r in range(3, rnum):\n ent_name = sheet.cell(row=r, column=2).value\n hangye = sheet.cell(row=r, column=3).value\n # print(ent_name)\n if ent_name is None:\n continue\n entInfo = {\"entName\": ent_name, \"hangye\": hangye}\n ent_list.append(entInfo)\n return ent_list\n\n def download(self, ent_name, hangye, year):\n # down_url = \"http://www.baidu.com/\" + parse.quote(ent_name) + \".pdf\"\n # self.download_file2(down_url, self.outPath.GetLabel())\n self.searchEnt(ent_name, hangye, year)\n return True\n\n def download_file1(self, url, store_path):\n filename = url.split(\"/\")[-1]\n filepath = os.path.join(store_path, filename)\n\n file_data = requests.get(url, allow_redirects=True).content\n with open(filepath, 'wb') as handler:\n handler.write(file_data)\n\n def download_file2(self, url, filename, store_path):\n while True:\n try:\n # store_path = store_path.encode(encoding='UTF-8',errors='strict')\n # filename = url.split(\"/\")[-1]\n filepath = os.path.join(store_path, filename)\n\n # def callbackfunc(blocknum, blocksize, totalsize):\n # percent = 100.0 * blocknum * blocksize / totalsize\n # if percent > 100:\n # percent = 100\n # self.area.AppendText(filename + \"下载进度:\" + str(percent) + \"%\\n\")\n self.area.AppendText(\"[\" + filename + \"]文件下载中...\\n\")\n urlretrieve(url, filepath)\n self.area.AppendText(\"[\" + filename + \"]文件下载完毕...\\n\")\n break\n except socket.timeout:\n count = 1\n while count <= 5:\n try:\n urllib.request.urlretrieve(url, filepath)\n break\n except socket.timeout:\n err_info = \"[\" + filename + ']下载超时,重新发起下载请求第%d次' % count\n print(err_info)\n self.area.AppendText(err_info + '\\n')\n count += 1\n if count > 5:\n print(\"downloading picture fialed!\")\n except urllib.error.HTTPError as e:\n self.area.AppendText(\"[\" + filename + \"]下载异常:\" + e.reason + '\\n')\n print(e.reason)\n print(e.code)\n time.sleep(3)\n\n def searchEnt(self, ent_name, hangye, year):\n header = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Referer': 'http://10.100.248.214/manager/reportInfo/list?hasReport=false',\n 'x-requested-with': 'XMLHttpRequest',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Accept-Encoding': 'gzip, deflate',\n 'Host': '10.100.248.214',\n 'Origin': 'http://10.100.248.214',\n 'Pragma': 'no-cache',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',\n 'Cookie': self.cookie.GetValue()\n }\n paramData = {\n 'industryName': '',\n 'industryCode': '',\n 'provinceCode': '',\n 'cityCode': '',\n 'countyCode': '',\n 'permitCode': '',\n 'companyName': ent_name,\n 'startFztime': '',\n 'endFztime': '',\n 'fzjg': False,\n 'first': '',\n 'isUpdate': '',\n 'page': 1\n }\n try:\n print(\"获取企业信息列表\")\n ret = requests.post('http://10.100.248.214/manager/reportInfo/list?hasReport=true', data=paramData,\n timeout=30, headers=header)\n # df = pd.read_html(ret.text)[0] # 该页面只返回一个表格,所以取第0个表格\n # print(\"获取企业HTML:@@@@@@@@@\", ret.text, \"&&&&&&&&&\")\n soup = BeautifulSoup(ret.text, 'html.parser')\n a_ctx = soup.findAll(\"a\", {'target': 'rightFrame'}) # 抓取a标签\n req_url2 = ''\n for ax in a_ctx:\n req_url2 = ax.get('href')\n print('获取到企业详情url', req_url2)\n\n if len(req_url2) <= 0:\n print('没有查询到企业')\n self.area.AppendText('没有查询到企业[' + ent_name + \"]信息\\n\")\n return\n req_url2 = 'http://10.100.248.214' + req_url2\n self.downloadPdf(ent_name, year, hangye, req_url2)\n\n except requests.exceptions.ConnectionError:\n self.area.AppendText('连接服务器超时\\n')\n print('[ERROR]ConnectionError -- will retry connect')\n\n def downloadPdf(self, ent_name, year, hangye, req_url2):\n header = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Referer': 'http://10.100.248.214/manager/reportInfo/list?hasReport=false',\n 'x-requested-with': 'XMLHttpRequest',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Accept-Encoding': 'gzip, deflate',\n 'Host': '10.100.248.214',\n 'Origin': 'http://10.100.248.214',\n 'Pragma': 'no-cache',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',\n 'Cookie': self.cookie.GetValue()\n }\n\n req_url3 = 'http://10.100.248.214/report/pdf/month?reportId=dataid&token=a247c4ab8ab04ff1b470c9ff3bdd95fb'\n try:\n # 获取2018年的数据\n print(\"年份:\", year)\n ret = requests.get(req_url2 + '&year=' + year, timeout=30, headers=header)\n\n # print('获取到数据HTML:@@@@@@@:', ret.text, \"&&&&&&&&\")\n soup = BeautifulSoup(ret.text, 'html.parser')\n s_ctx = soup.findAll(\"span\", {'class': 'page-count'}) # 抓取总条数\n a_ctx = soup.findAll(\"a\", {'class': 'btn-base btn-noborder icon-download'}) # 抓取a标签 获取数据id\n totalCount = int(s_ctx[0].contents[1])\n totalPage = int(totalCount / 10) + 1\n\n findFlag = False\n for ax in a_ctx:\n parent_text = ax.parent.parent.text\n if parent_text.find(\"年报\") == -1:\n continue\n\n data_herf = ax.get('href')\n if data_herf == '':\n continue\n data_id = re.findall(\"\\d+\", data_herf)[0]\n print('获取到数据id:', data_id)\n findFlag = True\n\n # 在循环内一个个开始下载文件\n req_url4 = req_url3.replace(\"dataid\", data_id)\n filePath = os.path.join(self.excelFile.GetValue(), year, hangye)\n self.download_file2(req_url4, ent_name + \".pdf\", filePath)\n\n if findFlag == False and totalPage > 1:\n time.sleep(0.3)\n for pageNo in (2, totalPage):\n ret = requests.get(req_url2 + '&year=' + year + '&pageNo=' + str(pageNo), timeout=30,\n headers=header)\n soup = BeautifulSoup(ret.text, 'html.parser')\n a_ctx = soup.findAll(\"a\", {'class': 'btn-base btn-noborder icon-download'})\n for ax in a_ctx:\n parent_text = ax.parent.parent.text\n if parent_text.find(\"年报\") == -1:\n continue\n data_herf = ax.get('href')\n if data_herf == '':\n continue\n data_id = re.findall(\"\\d+\", data_herf)[0]\n print('获取到数据id:', data_id)\n findFlag = True\n\n # 在循环内一个个开始下载文件\n req_url4 = req_url3.replace(\"dataid\", data_id)\n filePath = os.path.join(self.excelFile.GetValue(), year, hangye)\n self.download_file2(req_url4, ent_name + \".pdf\", filePath)\n if findFlag == True:\n break\n\n time.sleep(0.3)\n\n if findFlag == False:\n self.area.AppendText('企业[' + ent_name + \"]\" + year + \"没有年报,跳过下载\\n\")\n\n except requests.exceptions.ConnectionError:\n print('[ERROR]ConnectionError -- will retry connect')\n except Exception as ex:\n print(\"下载遇到遇到异常\")\n print(ex)\n\n\nclass mainApp(wx.App):\n def OnInit(self):\n self.SetAppName(APP_TITLE)\n self.Frame = mainFrame(None)\n self.Frame.Show()\n return True\n\n\nif __name__ == \"__main__\":\n app = mainApp()\n app.MainLoop()\n","sub_path":"DownloadTool.py","file_name":"DownloadTool.py","file_ext":"py","file_size_in_byte":18361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"36480825","text":"import collections\nimport inspect\nimport json\nimport os\n\n\ndef load_config_path(path='config',project_name='algo_trading_app'):\n # pwd = os.getcwd()\n pwd = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\n dirFound = os.path.isdir(os.path.join(pwd,path))\n while not dirFound and os.path.basename(pwd)!=project_name and pwd != os.path.realpath(os.path.join(pwd, '..')):\n pwd = os.path.realpath(os.path.join(pwd,os.pardir))\n dirFound = os.path.isdir(os.path.join(pwd,path))\n # One last check for Directory\n if not os.path.isdir(os.path.join(pwd,path)):\n raise IOError(\"Could not find {0} directory.\".format(path))\n return os.path.join(pwd,path)\n\n\ndef load_config_file(path='config', default_filename='default.cfg', project_name='algo_trading_app'):\n # Traverse upwards to find config path\n default_filename = 'default.cfg'\n custom_filename = 'custom.cfg'\n config_path = load_config_path(path=path,project_name=project_name)\n # Get default.cfg\n with open(os.path.join(config_path, default_filename), 'r') as f:\n default = json.load(f)\n\n if os.path.isfile(os.path.join(config_path,custom_filename)):\n try:\n with open(os.path.join(config_path, custom_filename), 'r') as f:\n custom = json.load(f)\n default = update_parameters(default,custom,add_new=True)\n except:\n print (\"Custom.cfg is empty or Could not resolve format of {0}. Make sure format mimics JSON format.\")\n return default\n\ndef get_path(name, forcepath=True, cfg=None):\n if cfg is None: cfg = load_config_file()\n try:\n if not isinstance(name,list): path = cfg['paths'].get(name,name)\n else: path = name\n if isinstance(path,(str,unicode)) and os.path.splitext(path)[-1]=='.path': # *.path file\n config_path = load_config_path()\n with open(os.path.join(config_path,path),'r') as f:\n path = f.read()\n return path\n elif isinstance(path,list): #\n path_list = list(path)\n path = ''\n for p in path_list:\n if os.path.isdir(os.path.join(path,p)) or (forcepath and p not in cfg['paths']):\n path = os.path.join(path,p)\n else:\n path = os.path.join(path,get_path(p,cfg=cfg))\n if os.path.isabs(path):\n return path\n else:\n return os.path.join(get_path(cfg['paths']['project'],cfg=cfg),path)\n except:\n raise IOError(\"Could not resolve path.\")\n\n\ndef get_params(*args,**kwargs):\n def _finditem(obj, key):\n if key in obj: return obj[key]\n for k, v in obj.items():\n if isinstance(v,dict):\n item = _finditem(v, key)\n if item is not None:\n return item\n cfg = kwargs.get('cfg',load_config_file())\n if len(args) > 1:\n res = []\n for arg in args:\n res.append(_finditem(cfg,arg))\n elif len(args)==1: res = _finditem(cfg,args[0])\n else: res = None\n return res\n\n\ndef update_parameters(parameters, new_parameters, add_new=False):\n for k, v in new_parameters.iteritems():\n if isinstance(v, collections.Mapping) and (add_new or k in parameters) and v is not None:\n parameter_subset = parameters.get(k, {})\n r = update_parameters(parameter_subset, v)\n parameters[k] = r\n else:\n parameters[k] = new_parameters[k]\n return parameters\n\n\n#--------------------------------------#\n### Generic File IO ###\n#--------------------------------------#\n\n\ndef load_file(name,asSeries=True,aslist=False,load_param_name=None,cfg=None,**kwargs):\n if cfg is None: cfg = load_config_file()\n if isinstance(name,list) and len(name) == 1: name = name[0]\n if not isinstance(name,list):\n res = cfg['files'].get(name,name)\n else:\n res = name\n full_filename = get_path(res)\n ext = os.path.splitext(full_filename)[-1]\n if ext in cfg['extension_mappings']['.csv']:\n if load_param_name is None :\n if not isinstance(name, list):\n load_param_name = name\n else:\n load_param_name = name[-1]\n csv2df_kwargs = cfg['load_kwargs'].get(load_param_name,{})\n csv2df_kwargs.update(kwargs)\n res = pd.read_csv(full_filename,**csv2df_kwargs)\n if asSeries and res.ndim > 1 and len(res.columns) == 1: res = res[res.columns[0]]\n if aslist: res = res.values.ravel().tolist()\n elif ext in cfg['extension_mappings']['.json']:\n with open(full_filename,'r') as f:\n res = json.load(f)\n else:\n with open(full_filename,'r') as f:\n res = f\n return res\n\n\ndef save_file(name,data,cfg=None,astype=None,**kwargs):\n if cfg is None:cfg = load_config_file()\n if not isinstance(name,list):\n res = cfg['files'].get(name,None)\n else:\n res = name\n name = ''\n if res is None: return False\n if isinstance(res,list):\n dir_name,filename = res[:-1],res[-1]\n dir_name = dir_name[0] if len(dir_name) == 1 else dir_name\n else:\n dir_name,filename = get_path(name='project_path',cfg=cfg),res\n full_filename = os.path.join(get_path(name=dir_name,cfg=cfg),filename)\n ext = os.path.splitext(full_filename)[-1]\n if ext in cfg['extension_mappings']['.csv'] or \\\n (astype is not None and astype in cfg['extension_mappings']['.csv']):\n if isinstance(data,(pd.core.frame.DataFrame,pd.core.series.Series)):\n df2csv_kwargs = cfg['save_kwargs'].get(name,{})\n df2csv_kwargs.update(kwargs)\n data.to_csv(full_filename,**df2csv_kwargs)\n return True\n elif ext in cfg['extension_mappings']['.json'] or \\\n (astype is not None and astype in cfg['extension_mappings']['.json']):\n with open(full_filename,'w') as f:\n json.dump(data,f,indent=2)\n return True\n else:\n return False\n\n\n\ndef load_key(key_name,cfg=None):\n if cfg is None: cfg = load_config_file()\n res = cfg['keys'].get(key_name, None)\n if res is None:\n raise KeyError(\"{0} not contained in default.cfg \\\"keys\\\".\".format(key_name))\n if isinstance(res,list):\n dir_name,filename = res[:-1],res[-1]\n full_filename = os.path.join(get_path(name=dir_name,cfg=cfg),filename)\n else:\n full_filename = os.path.join(get_path('keys', cfg=cfg), res)\n ext = os.path.splitext(full_filename)[-1]\n if ext == '.json':\n with open(full_filename,'r') as f:\n res = json.load(f)\n elif ext == '.key': #\n with open(full_filename,'r') as f:\n res = f.read()\n else:\n raise TypeError('{0} value is not in correct format.'.format(key_name))\n return res","sub_path":"utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"115888766","text":"import datetime\nimport numbers\nimport threading\nimport functools\nimport bisect\n\nclass TimerManager:\n\t'''\\\n\tTimer manager class.\n\t'''\n\n\tdef __init__(self):\n\t\tself.mutex = threading.RLock()\n\t\tself.delayed_commands = []\n\n\tdef _schedule_command(self, command):\n\t\twith self.mutex:\n\t\t\tbisect.insort(self.delayed_commands, command)\n\n\t\t\t# signal~\n\t\t\tfrom . import bot\n\t\t\tif bot:\n\t\t\t\tbot.signal('bot::scheduled', command.delay.total_seconds(), command.function)\n\n\tdef check(self):\n\t\t'''\\\n\t\tCheck if any of our delayed commands need to be run.\n\n\t\tUsually called from :meth:`.Bot.process_once`.\n\t\t'''\n\n\t\twith self.mutex:\n\t\t\twhile self.delayed_commands:\n\t\t\t\tcommand = self.delayed_commands[0]\n\t\t\t\tif not command.due():\n\t\t\t\t\tbreak\n\t\t\t\tcommand.function()\n\t\t\t\tif isinstance(command, PeriodicCommand):\n\t\t\t\t\tself._schedule_command(command.next())\n\t\t\t\tdel self.delayed_commands[0]\n\n\tdef execute_at(self, at, function, args=(), kwargs={}):\n\t\t'''\n\t\tExecute a function at a specified time.\n\t\t'''\n\n\t\tfunction = functools.partial(function, *args, **kwargs)\n\t\tself._schedule_command(DelayedCommand.at_time(at, function))\n\n\tdef execute_delayed(self, delay, function, args=(), kwargs={}):\n\t\t'''\n\t\tExecute a function after a specified time.\n\t\t'''\n\n\t\tfunction = functools.partial(function, *args, **kwargs)\n\t\tself._schedule_command(DelayedCommand.after(delay, function))\n\n\tdef execute_every(self, period, function, args=(), kwargs={}):\n\t\t'''\n\t\tExecute a function every `period` seconds.\n\t\t'''\n\n\t\tfunction = functools.partial(function, *args, **kwargs)\n\t\tself._schedule_command(PeriodicCommand.after(period, function))\n\nclass DelayedCommand(datetime.datetime):\n\t'''\n\tA command to be executed after some delay (seconds or timedelta).\n\n\tClients may override .now() to have dates interpreted in a different\n\tmanner, such as to use UTC or to have timezone-aware times.\n\t'''\n\n\t@classmethod\n\tdef now(cls, tzinfo=None):\n\t\treturn datetime.datetime.now(tzinfo)\n\n\t@classmethod\n\tdef from_datetime(cls, other):\n\t\treturn cls(other.year, other.month, other.day, other.hour,\n\t\t\tother.minute, other.second, other.microsecond,\n\t\t\tother.tzinfo)\n\n\t@classmethod\n\tdef after(cls, delay, function):\n\t\tif not isinstance(delay, datetime.timedelta):\n\t\t\tdelay = datetime.timedelta(seconds=delay)\n\n\t\tdue_time = cls.now() + delay\n\t\tcmd = cls.from_datetime(due_time)\n\t\tcmd.delay = delay\n\t\tcmd.function = function\n\t\treturn cmd\n\n\t@classmethod\n\tdef at_time(cls, at, function):\n\t\t'''\n\t\tConstruct a DelayedCommand to come due at `at`, where `at` may be\n\t\ta datetime or timestamp. If `at` is a real number, it will be\n\t\tinterpreted as a naive local timestamp.\n\t\t'''\n\n\t\tif isinstance(at, numbers.Real):\n\t\t\tat = datetime.datetime.fromtimestamp(at)\n\n\t\tcmd = cls.from_datetime(at)\n\t\tcmd.delay = at - cmd.now()\n\t\tcmd.function = function\n\t\treturn cmd\n\n\tdef due(self):\n\t\treturn self.now() >= self\n\nclass PeriodicCommand(DelayedCommand):\n\t'''\n\tLike a delayed command, but expect this command to run every delay\n\tseconds.\n\t'''\n\n\tdef next(self):\n\t\tcmd = self.__class__.from_datetime(self + self.delay)\n\t\tcmd.delay = self.delay\n\t\tcmd.function = self.function\n\t\treturn cmd\n\n\tdef __setattr__(self, key, value):\n\t\tif key == 'delay' and not value > datetime.timedelta():\n\t\t\traise ValueError('A PeriodicCommand must have a positive, non-zero delay.')\n\t\tsuper(PeriodicCommand, self).__setattr__(key, value)\n","sub_path":"xbotpp/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"599761765","text":"#!/usr/bin/python3\n# -*- coding=utf-8 -*-\n\n\n\n\nfrom ssh_client import ssh_client_no_async\n\nimport gevent\nfrom gevent import monkey\n\nmonkey.patch_all()\n\n\ndef get_ssh_result(i):\n print(\"start\", i)\n result = ssh_client_no_async('localhost', 'root', 'Cisc0123', 'ls / -an', asy_id=i)\n print(\"end\", i)\n return result\n\n\ntasks = [gevent.spawn(get_ssh_result, i) for i in range(3)]\nall_result = gevent.joinall(tasks)\nfor x in all_result:\n print(x.get())\n\n # print(x.get().text)\n\n","sub_path":"python基础/多线程多进程/coroutine_2_ssh.py","file_name":"coroutine_2_ssh.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"339722331","text":"\"\"\"\nLabour work #1.1\nCount frequencies dictionary by the given arbitrary text\n\"\"\"\ndef calculate_frequences(text: str) -> dict:\n \"\"\"\n Calculates number of times each word appears in the text\n \"\"\"\n prohibited_marks = ['-','.',',','!','?','\"',\"'\", ':',';']\n splitted = (text.replace('\\n', ' ')).split(' ')\n res = []\n for word in splitted:\n if not word.isdigit() and word not in prohibited_marks:\n clear_word = ''\n for el in word:\n if el not in prohibited_marks:\n clear_word += el\n if clear_word is not '':\n res.append(clear_word)\n frequencies = {}\n for key in res:\n if key in frequencies:\n value = frequencies[key]\n frequencies[key] = value+1\n else:\n frequencies[key]=1\n return frequencies\n pass\n\n\ndef filter_stop_words(frequencies: dict, stop_words: tuple) -> dict:\n \"\"\"\n Removes all stop words from the given frequencies dictionary\n \"\"\"\n for key in list(frequencies.keys()):\n if key in stop_words:\n del frequencies[key]\n return frequencies\n pass\n\ndef get_top_n(frequencies: dict, top_n: int) -> tuple:\n \"\"\"\n Takes first N popular words\n \"\"\"\n list_dict = list(frequencies.items())\n list_dict.sort(key=lambda i: (i[1],i[0]), reverse=True)\n ind = 0\n done = list()\n for i in list_dict:\n if ind < top_n:\n done.append(list_dict[ind])\n ind += 1\n else:\n break\n print (done)\n pass\n\n\nstart = open ('text.txt', 'r')\ntext = start.read().lower()\n\ndict = calculate_frequences(text)\nstop_words = stop_words = ('ourselves', 'hers', 'between', 'yourself', 'but', 'again', 'there', 'about', \n'once', 'during', 'out', 'very', 'having', 'with', 'they', 'own', 'an', 'be', \n'some', 'for', 'do', 'its', 'yours', 'such', 'into', 'of', 'most', 'itself', \n'other', 'off', 'is', 's', 'am', 'or', 'who', 'as', 'from', 'him', 'each', 'the', \n'themselves', 'until', 'below', 'are', 'we', 'these', 'your', 'his', 'through', \n'don', 'nor', 'me', 'were', 'her', 'more', 'himself', 'this', 'down', 'should', \n'our', 'their', 'while', 'above', 'both', 'up', 'to', 'ours', 'had', 'she', 'all', \n'no', 'when', 'at', 'any', 'before', 'them', 'same', 'and', 'been', 'have', 'in', \n'will', 'on', 'does', 'yourselves', 'then', 'that', 'because', 'what', 'over', \n'why', 'so', 'can', 'did', 'not', 'now', 'under', 'he', 'you', 'herself', 'has', \n'just', 'where', 'too', 'only', 'myself', 'which', 'those', 'i', 'after', 'few', \n'whom', 't', 'being', 'if', 'theirs', 'my', 'against', 'a', 'by', 'doing', \n'it', 'how', 'further', 'was', 'here', 'than')\nprint (filter_stop_words(dict, stop_words))\n\ndict_clear = filter_stop_words(dict, stop_words)\ntop_n = 5\nget_top_n(dict_clear, top_n) \n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"326632629","text":"from panda3d.core import Point3\nfrom panda3d.core import Vec2, Vec3\nfrom panda3d.core import CollisionCapsule\n\nfrom wecs.core import Component\nfrom wecs.aspects import Aspect\nfrom wecs.aspects import factory\nfrom wecs import panda3d\nfrom wecs import mechanics\nfrom wecs.panda3d import aspects\n\n\n# Ignore this for the moment please; It means \"This entity's model can be collided into\".\n@Component()\nclass Map:\n pass\n\n\n# Ignore this too; It makes the map collidable.\nclass LoadMapsAndActors(panda3d.LoadModels):\n def post_load_hook(self, node, entity):\n if Map in entity:\n node.flatten_strong()\n node.set_collide_mask(1<<0)\n\n\n# Each frame, run these systems. This defines the game itself.\nsystem_types = [\n LoadMapsAndActors, # Self-descriptive...\n panda3d.DetermineTimestep, # How long is this frame? Update all clocks.\n # What movement do the characters intend to do?\n panda3d.AcceptInput, # Input from player, ranges ([-1; 1]), not scaled for time.\n panda3d.Think, # Input from AIs, the same\n mechanics.UpdateStamina, # A game mechanic that cancels move modes if the character is exhausted, \"unintending\" them\n panda3d.TurningBackToCamera, # Characters can have a tendency towards walk towards away-from-camera that adjusts their intention.\n panda3d.UpdateCharacter, # Scale inputs by frame time, making them \"Intended movement in this frame.\"\n # The following systems adjust the intended movement\n panda3d.Floating, # Scale by speed for floating\n panda3d.Walking, # Scale by speed for walk / run / crouch / sprint\n panda3d.Inertiing, # Clamp movement speed delta by inertia\n panda3d.Bumping, # Bump into things (and out again).\n panda3d.Falling, # Fall, or stand on the ground.\n panda3d.Jumping, # Impart upward impulse.\n panda3d.ExecuteMovement, # Turn intention into actual movement\n # We're done with character movement, now adjust the cameras.\n panda3d.UpdateCameras,\n panda3d.CollideCamerasWithTerrain,\n]\n\n\n\ngame_map = Aspect([panda3d.Position, panda3d.Model, panda3d.Scene, Map],\n overrides={\n panda3d.Position: dict(value=factory(lambda:Point3(0, 0, 0))),\n panda3d.Model: dict(model_name='roadE.bam'),\n panda3d.Scene: dict(node=base.render),\n },\n)\n\n\n# Populate the world with the map, the player character, and a few NPCs\n\n# Map\ngame_map.add(base.ecs_world.create_entity())\n\n# Player\nplayer_avatar = Aspect([aspects.player_character, mechanics.Stamina])\nplayer_avatar.add(\n base.ecs_world.create_entity(),\n overrides={panda3d.Position: dict(value=Point3(50, 290, 0))},\n)\n\n# Non-moving NPC\naspects.non_player_character.add(\n base.ecs_world.create_entity(),\n overrides={panda3d.Position: dict(value=Point3(60, 290, 0))},\n)\n\n# Small circle NPC\naspects.non_player_character.add(\n base.ecs_world.create_entity(),\n overrides={\n panda3d.Position: dict(value=Point3(70, 290, 0)),\n panda3d.ConstantCharacterAI: dict(\n move=Vec3(0.0, 0.25, 0.0),\n heading=-0.5,\n ),\n },\n)\n\n# Brownian NPC\nnew_npc = Aspect([aspects.avatar, aspects.npc_mind_brownian])\nnew_npc.add(\n base.ecs_world.create_entity(),\n overrides={panda3d.Position: dict(value=Point3(80, 290, 0))},\n)\n","sub_path":"examples/panda3d-character-controller/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"405950872","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef seam(left, right, pts1, pts2):\n\tprint('--- seam ---')\n\t# exit()\n\th=left.shape[0]\n\tw1=left.shape[1]\n\tw2=right.shape[1]\n\tlefteng = rgb2gray(left)[:,pts1[0,0]:]\n\trighteng = rgb2gray(right)[:,:pts2[3,0]+1]\n\t# exit()\n\tMx, Tbx = cumMinEngVer(lefteng, righteng)\n\tresult = np.zeros((h,(w1+w2)-(w1-pts1[0,0]+1),3))\n\n\tE = min(Mx[h-1,:])\n\ty=np.where(Mx[h-1,:]==E)[0][0]\n\tremove = [(h-1,y+pts1[0,0])]\n\tw=(w1+w2)-(w1-pts1[0,0]+1)\n\tfor i in range(h-2,-1,-1):\n\t\ty=y+Tbx[i+1,y]\n\t\tremove+=[(i,y+pts1[0,0])]\n\n\tfor i in range(h):\n\t\tskip = 0\n\t\tfor j in range(w):\n\t\t\tif (i,j) in remove:\n\t\t\t\tskip = 1\n\t\t\tfor k in range(3):\n\t\t\t\tif skip == 1:\n\t\t\t\t\tassert j-pts1[0,0] >= 0\n\t\t\t\t\tresult[i,j,k] = right[i,j-pts1[0,0],k]\n\t\t\t\telse:\n\t\t\t\t\tresult[i,j,k] = left[i,j,k]\n\treturn result.astype('uint8')\n\ndef rgb2gray(rgb):\n return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])\n\ndef cumMinEngVer(lefteng, righteng):\n # Your Code Here\n e=abs(lefteng-righteng)\n n=e.shape[0]\n m=e.shape[1]\n Mx, Tbx = np.zeros((n,m)), np.zeros((n,m),dtype=int)\n Mx[0,:] = e[0,:]\n for i in range(1, n):\n for j in range(m):\n value = min(Mx[i-1,max(j-1,0)],Mx[i-1,j],Mx[i-1,min(j+1,m-1)])\n Mx[i,j]=e[i,j]+value\n if j-1>= 0 and Mx[i-1,j-1] == value:\n Tbx[i,j]=-1\n elif j+1 <= m-1 and Mx[i-1,j+1] == value:\n Tbx[i,j]=1\n return Mx, Tbx","sub_path":"image_stitch/submission 3_extra credit/seam.py","file_name":"seam.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"427946846","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom typing import Dict, List, Optional\n\nimport torch\nimport torch.nn as nn\nfrom fairseq import search, utils\nfrom fairseq.data import data_utils\nfrom fairseq.models import FairseqIncrementalDecoder\nfrom fairseq.models.fairseq_encoder import EncoderOut\nfrom torch import Tensor\n\nfrom fairseq.sequence_generator import SequenceGenerator\n\nclass SLUSequenceGenerator(SequenceGenerator):\n\n def __init__(\n self,\n models,\n tgt_dict,\n beam_size=1,\n max_len_a=0.3,\n max_len_b=10,\n min_len=1,\n normalize_scores=True,\n len_penalty=1.0,\n unk_penalty=0.0,\n retain_dropout=False,\n temperature=1.0,\n match_source_len=False,\n no_repeat_ngram_size=0,\n search_strategy=None,\n eos=None,\n ):\n # beam_size=1, This is not a beam-search generator\n super().__init__(\n models,\n tgt_dict,\n beam_size=1,\n max_len_a=max_len_a,\n max_len_b=max_len_b,\n min_len=min_len,\n normalize_scores=normalize_scores,\n len_penalty=len_penalty,\n unk_penalty=unk_penalty,\n retain_dropout=retain_dropout,\n temperature=temperature,\n match_source_len=match_source_len,\n no_reapat_ngram_size=no_repeat_ngram_size,\n search_strategy=search_strategy,\n eos=eos,\n )\n\n def _generate(\n self,\n sample: Dict[str, Dict[str, Tensor]],\n prefix_tokens: Optional[Tensor] = None,\n bos_token: Optional[int] = None,\n ):\n\n encoder_input: Dict[str, Tensor] = {}\n for k, v in sample[\"net_input\"].items():\n if k != \"prev_output_tokens\":\n encoder_input[k] = v\n\n src_tokens = encoder_input[\"src_tokens\"]\n # length of the source text being the character length except EndOfSentence and pad\n '''src_lengths = (\n (src_tokens.ne(self.eos) & src_tokens.ne(self.pad)).long().sum(dim=1)\n )'''\n src_lengths = encoder_input[\"src_lengths\"]\n\n # bsz: total number of sentences in beam\n input_size = src_tokens.size()\n bsz, src_len = input_size[0], input_size[1]\n beam_size = 1 #self.beam_size # No beam search\n\n max_len: int = -1\n if self.match_source_len:\n max_len = src_lengths.max().item()\n else:\n max_len = min(\n int(self.max_len_a * src_len + self.max_len_b),\n # exclude the EOS marker\n self.model.max_decoder_positions() - 1,\n )\n assert (\n self.min_len <= max_len\n ), \"min_len cannot be larger than max_len, please adjust these!\"\n\n # compute the encoder output for each beam\n encoder_outs = self.model.forward_encoder(\n src_tokens=encoder_input[\"src_tokens\"],\n src_lengths=encoder_input[\"src_lengths\"],\n )\n\n if beam_size > 1:\n # placeholder of indices for bsz * beam_size to hold tokens and accumulative scores\n new_order = torch.arange(bsz).view(-1, 1).repeat(1, beam_size).view(-1)\n new_order = new_order.to(src_tokens.device).long()\n encoder_outs = self.model.reorder_encoder_out(encoder_outs, new_order)\n # ensure encoder_outs is a List.\n assert encoder_outs is not None\n\n # initialize buffers\n scores = (\n torch.zeros(bsz * beam_size, max_len + 1).to(src_tokens).float()\n ) # +1 for eos; pad is never choosed for scoring\n tokens = (\n torch.zeros(bsz * beam_size, max_len + 2)\n .to(src_tokens)\n .long()\n .fill_(self.pad)\n ) # +2 for eos and pad\n tokens[:, 0] = self.eos if bos_token is None else bos_token\n attn: Optional[Tensor] = None\n\n # The blacklist indicates candidates that should be ignored.\n # For example, suppose we're sampling and have already finalized 2/5\n # samples. Then the blacklist would mark 2 positions as being ignored,\n # so that we only finalize the remaining 3 samples.\n blacklist = (\n torch.zeros(bsz, beam_size).to(src_tokens).eq(-1)\n ) # forward and backward-compatible False mask\n\n # list of completed sentences\n finalized = torch.jit.annotate(\n List[List[Dict[str, Tensor]]],\n [torch.jit.annotate(List[Dict[str, Tensor]], []) for i in range(bsz)],\n ) # contains lists of dictionaries of infomation about the hypothesis being finalized at each step\n\n finished = [\n False for i in range(bsz)\n ] # a boolean array indicating if the sentence at the index is finished or not\n num_remaining_sent = bsz # number of sentences remaining\n\n # number of candidate hypos per step\n cand_size = 2 * beam_size # 2 x beam size in case half are EOS # ??? I don't understand !\n\n # offset arrays for converting between different indexing schemes\n bbsz_offsets = (torch.arange(0, bsz) * beam_size).unsqueeze(1).type_as(tokens)\n cand_offsets = torch.arange(0, cand_size).type_as(tokens)\n\n reorder_state: Optional[Tensor] = None\n batch_idxs: Optional[Tensor] = None\n for step in range(max_len + 1): # one extra step for EOS marker\n # reorder decoder internal states based on the prev choice of beams\n # print(f'step: {step}')\n if reorder_state is not None:\n if batch_idxs is not None:\n # update beam indices to take into account removed sentences\n corr = batch_idxs - torch.arange(batch_idxs.numel()).type_as(\n batch_idxs\n )\n reorder_state.view(-1, beam_size).add_(\n corr.unsqueeze(-1) * beam_size\n )\n self.model.reorder_incremental_state(reorder_state)\n encoder_outs = self.model.reorder_encoder_out(\n encoder_outs, reorder_state\n )\n\n lprobs, avg_attn_scores = self.model.forward_decoder(\n tokens[:, : step + 1], encoder_outs, self.temperature\n )\n lprobs[lprobs != lprobs] = torch.tensor(-math.inf).to(lprobs) # ??? WTF ???\n\n lprobs[:, self.pad] = -math.inf # never select pad\n lprobs[:, self.unk] -= self.unk_penalty # apply unk penalty\n\n # handle max length constraint\n if step >= max_len:\n lprobs[:, : self.eos] = -math.inf\n lprobs[:, self.eos + 1 :] = -math.inf\n\n #tokens[:, step + 1] = lprobs.argmax(-1)\n\n # handle prefix tokens (possibly with different lengths)\n prefix_tokens = None # NOTE: exclude this for DEBUGGING\n if (\n prefix_tokens is not None\n and step < prefix_tokens.size(1)\n and step < max_len\n ):\n lprobs, tokens, scores = self._prefix_tokens(\n step, lprobs, scores, tokens, prefix_tokens, beam_size\n )\n elif step < self.min_len:\n # minimum length constraint (does not apply if using prefix_tokens)\n lprobs[:, self.eos] = -math.inf\n\n # Record attention scores, only support avg_attn_scores is a Tensor\n if avg_attn_scores is not None:\n if attn is None:\n attn = torch.empty(\n bsz * beam_size, avg_attn_scores.size(1), max_len + 2\n ).to(scores)\n attn[:, :, step + 1].copy_(avg_attn_scores)\n\n scores = scores.type_as(lprobs)\n eos_bbsz_idx = torch.empty(0).to(\n tokens\n ) # indices of hypothesis ending with eos (finished sentences)\n eos_scores = torch.empty(0).to(\n scores\n ) # scores of hypothesis ending with eos (finished sentences)\n\n if False: #self.no_repeat_ngram_size > 0: # NOTE: exclude this for DEBUGGING\n lprobs = self._no_repeat_ngram(tokens, lprobs, bsz, beam_size, step)\n\n cand_scores, cand_indices = lprobs.max(1)\n cand_beams = torch.LongTensor( [0] * bsz ).to(cand_indices)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"SLU/fairseq/fairseq/SLUSequenceGenerator.py","file_name":"SLUSequenceGenerator.py","file_ext":"py","file_size_in_byte":8565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"575674762","text":"# Copyright 2021 Zhongyang Zhang\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nimport torch\nimport torch.nn as nn\n\n\ndef conv3x3(in_channels, out_channels, kernel_size, bias=True, stride=1):\n return nn.Conv2d(\n in_channels, out_channels, kernel_size,\n padding=(kernel_size//2), bias=bias, stride=stride)\n\n\ndef mean_shift_1d(data, mean, std, base=1, add=False):\n if add:\n data = data * std / base + mean\n else:\n data = (data - mean) / std * base\n return data\n\n\ndef mean_shift_2d(data, mean, std, base=1, add=False):\n data = data.permute(2, 3, 0, 1)\n\n if add:\n data = data * std / base + mean\n else:\n data = (data - mean) / std * base\n return data.permute(2, 3, 0, 1)\n\n\nclass BasicBlock(nn.Sequential):\n def __init__(\n self, in_channels, out_channels, kernel_size, stride=1, bias=True,\n bn=False, act=nn.ReLU(True)):\n\n m = [nn.Conv2d(\n in_channels, out_channels, kernel_size,\n padding=(kernel_size//2), stride=stride, bias=bias)\n ]\n if bn:\n m.append(nn.BatchNorm2d(out_channels))\n if act is not None:\n m.append(act)\n super(BasicBlock, self).__init__(*m)\n\n\nclass ResBlock(nn.Module):\n def __init__(\n self, conv, n_feats, kernel_size,\n bias=True, bn=False, act=nn.ReLU(True), res_scale=1):\n\n super(ResBlock, self).__init__()\n m = []\n for i in range(2):\n m.append(conv(n_feats, n_feats, kernel_size, bias=bias))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n if i == 0:\n m.append(act)\n\n self.body = nn.Sequential(*m)\n self.res_scale = res_scale\n\n def forward(self, x):\n res = self.body(x).mul(self.res_scale)\n res += x\n return res\n\n\nclass Upsampler(nn.Sequential):\n def __init__(self, conv, scale, n_feats, bn=False, act=False, bias=True):\n\n m = []\n if scale in (2, 4, 8): # Is scale = 2^n?\n for _ in range(int(math.log(scale, 2))):\n m.append(conv(n_feats, 4 * n_feats, 3, bias))\n m.append(nn.PixelShuffle(2))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n\n if act == 'relu':\n m.append(nn.ReLU(True))\n elif act == 'prelu':\n m.append(nn.PReLU(n_feats))\n\n elif scale == 3:\n m.append(conv(n_feats, 9 * n_feats, 3, bias))\n m.append(nn.PixelShuffle(3))\n if bn:\n m.append(nn.BatchNorm2d(n_feats))\n\n if act == 'relu':\n m.append(nn.ReLU(True))\n elif act == 'prelu':\n m.append(nn.PReLU(n_feats))\n else:\n raise NotImplementedError\n\n super(Upsampler, self).__init__(*m)\n\n\n## ---------------------- RDB Modules ------------------------ ##\nclass RDB_Conv(nn.Module):\n \"\"\" Residual Dense Convolution.\n \"\"\"\n\n def __init__(self, inChannels, growRate, kSize=3):\n super(RDB_Conv, self).__init__()\n Cin = inChannels\n G = growRate\n self.conv = nn.Sequential(*[\n nn.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1),\n nn.ReLU()\n ])\n\n def forward(self, x):\n out = self.conv(x)\n return torch.cat((x, out), 1)\n\n\nclass RDB(nn.Module):\n \"\"\" Residual Dense Block.\n \"\"\"\n\n def __init__(self, growRate0, growRate, nConvLayers, kSize=3):\n super(RDB, self).__init__()\n G0 = growRate0\n G = growRate\n C = nConvLayers\n\n convs = []\n for c in range(C):\n convs.append(RDB_Conv(G0 + c * G, G))\n self.convs = nn.Sequential(*convs)\n\n # Local Feature Fusion\n self.LFF = nn.Conv2d(G0 + C * G, G0, 1, padding=0, stride=1)\n\n def forward(self, x):\n return self.LFF(self.convs(x)) + x\n","sub_path":"model/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"341809278","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass TfvcChangesetSearchCriteria(Model):\n \"\"\"TfvcChangesetSearchCriteria.\n\n :param author: Alias or display name of user who made the changes\n :type author: str\n :param follow_renames: Whether or not to follow renames for the given item being queried\n :type follow_renames: bool\n :param from_date: If provided, only include changesets created after this date (string) Think of a better name for this.\n :type from_date: str\n :param from_id: If provided, only include changesets after this changesetID\n :type from_id: int\n :param include_links: Whether to include the _links field on the shallow references\n :type include_links: bool\n :param item_path: Path of item to search under\n :type item_path: str\n :param to_date: If provided, only include changesets created before this date (string) Think of a better name for this.\n :type to_date: str\n :param to_id: If provided, a version descriptor for the latest change list to include\n :type to_id: int\n \"\"\"\n\n _attribute_map = {\n 'author': {'key': 'author', 'type': 'str'},\n 'follow_renames': {'key': 'followRenames', 'type': 'bool'},\n 'from_date': {'key': 'fromDate', 'type': 'str'},\n 'from_id': {'key': 'fromId', 'type': 'int'},\n 'include_links': {'key': 'includeLinks', 'type': 'bool'},\n 'item_path': {'key': 'itemPath', 'type': 'str'},\n 'to_date': {'key': 'toDate', 'type': 'str'},\n 'to_id': {'key': 'toId', 'type': 'int'}\n }\n\n def __init__(self, author=None, follow_renames=None, from_date=None, from_id=None, include_links=None, item_path=None, to_date=None, to_id=None):\n super(TfvcChangesetSearchCriteria, self).__init__()\n self.author = author\n self.follow_renames = follow_renames\n self.from_date = from_date\n self.from_id = from_id\n self.include_links = include_links\n self.item_path = item_path\n self.to_date = to_date\n self.to_id = to_id\n","sub_path":"vsts/vsts/tfvc/v4_0/models/tfvc_changeset_search_criteria.py","file_name":"tfvc_changeset_search_criteria.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651729534","text":"import torch\nfrom torch import nn\nfrom einops.layers.torch import Reduce\n\nsequencer_settings = {\n 'S': [[4, 3, 8, 3], [192, 384, 384, 384], [48, 96, 96, 96], 3],\n 'M': [[4, 3, 14, 3], [192, 384, 384, 384], [48, 96, 96, 96], 3],\n 'L': [[8, 8, 16, 4], [192, 384, 384, 384], [48, 96, 96, 96], 3]\n}\n\nclass PatchEmbedOverlap(nn.Module):\n \"\"\"Image to Patch Embedding with overlapping\n \"\"\"\n def __init__(self, patch_size=16, stride=16, padding=0, embed_dim=768):\n super().__init__()\n self.proj = nn.Conv2d(3, embed_dim, patch_size, stride, padding)\n self.norm = nn.BatchNorm2d(embed_dim)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.norm(self.proj(x))\n\nclass PreNormResidual(nn.Module):\n def __init__(self, dim, fn):\n super().__init__()\n self.fn = fn\n self.norm = nn.LayerNorm(dim)\n\n def forward(self, x):\n return self.fn(self.norm(x)) + x\n\nclass BiLSTM2D(nn.Module):\n def __init__(self, d_model, hidden_d_model):\n super().__init__()\n self.rnn_v = nn.LSTM(d_model, hidden_d_model, num_layers = 1, batch_first = True, bias = True, bidirectional = True)\n self.rnn_h = nn.LSTM(d_model, hidden_d_model, num_layers = 1, batch_first = True, bias = True, bidirectional = True)\n self.fc = nn.Linear(4 * hidden_d_model, d_model)\n \n def forward(self, x):\n B, H, W, C = x.shape\n v, _ = self.rnn_v(x.permute(0, 2, 1, 3).reshape(-1, H, C))\n v = v.reshape(B, W, H, -1).permute(0, 2, 1, 3)\n h, _ = self.rnn_h(x.reshape(-1, W, C))\n h = h.reshape(B, H, W, -1)\n x = torch.cat([v, h], dim = -1)\n x = self.fc(x)\n return x\n\n\nclass Sequencer2DBlock(nn.Module):\n def __init__(self, d_model, depth, hidden_d_model, expansion_factor = 3, dropout = 0.):\n super().__init__()\n\n self.model = nn.Sequential(\n *[nn.Sequential(\n PreNormResidual(d_model, nn.Sequential(\n BiLSTM2D(d_model, hidden_d_model)\n )),\n PreNormResidual(d_model, nn.Sequential(\n nn.Linear(d_model, d_model * expansion_factor),\n nn.GELU(),\n nn.Dropout(dropout),\n nn.Linear(d_model * expansion_factor, d_model),\n nn.Dropout(dropout)\n ))\n ) for _ in range(depth)]\n )\n\n def forward(self, x):\n x = x.permute(0, 2, 3, 1)\n x = self.model(x)\n x = x.permute(0, 3, 1, 2)\n return x\n\nclass Sequencer2D(nn.Module):\n def __init__(self, model_name: str = 'M', pretrained: str = None, num_classes: int = 1000, in_channels = 3, *args, **kwargs) -> None:\n super().__init__()\n assert model_name in sequencer_settings.keys(), f\"Sequencer model name should be in {list(sequencer_settings.keys())}\"\n depth, embed_dims, hidden_dims, expansion_factor = sequencer_settings[model_name]\n\n self.patch_size = [7, 2, 1, 1]\n\n self.stage = len(depth)\n self.stages = nn.Sequential(\n *[nn.Sequential(\n nn.Conv2d(in_channels if i == 0 else embed_dims[i - 1], embed_dims[i], kernel_size=self.patch_size[i], stride=self.patch_size[i]),\n Sequencer2DBlock(embed_dims[i], depth[i], hidden_dims[i], expansion_factor, dropout = 0.)\n ) for i in range(self.stage)]\n )\n\n self.mlp_head = nn.Sequential(\n Reduce('b c h w -> b c', 'mean'),\n nn.Linear(embed_dims[-1], num_classes)\n )\n\n def forward(self, x):\n embedding = self.stages(x)\n out = self.mlp_head(embedding)\n return out\n\nif __name__ == '__main__':\n model = Sequencer2D('L')\n x = torch.randn(1, 3, 224, 224)\n y = model(x)\n print(y.shape)\n\n\n total_params = sum(p.numel() for p in model.parameters())\n print(f'{total_params:,} total parameters.')\n total_trainable_params = sum(\n p.numel() for p in model.parameters() if p.requires_grad)\n print(f'{total_trainable_params:,} training parameters.')","sub_path":"models_pytorch/sequencer.py","file_name":"sequencer.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"346480238","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis spider is a DeerFoot spider created on top of the ATSSpider\nscrapy crawl deerfoot -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.deerfoot.co.uk/vacancies?field_job_type_value=0&field_location_tid=All&title=\"\n\nsample url:\nhttp://www.deerfoot.co.uk/vacancies?field_job_type_value=0&field_location_tid=All&title=\n\"\"\"\n\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix\n\n\nclass DeerFoot(ATSSpider):\n\n name = \"deerfoot\"\n ref_re = compile(r\"(\\d+)\")\n\n def parse(self, response):\n sel = Selector(response)\n jobtypes = sel.xpath('//select[@name=\"field_job_type_value\"]/option')\n for _type in jobtypes:\n _type_value = _type.xpath('./@value').extract()\n if _type_value:\n _type_url = sub(\n 'field_job_type_value=\\d+',\n 'field_job_type_value=%s' % _type_value[0],\n response.url\n )\n yield Request(\n _type_url, callback=self.parse_jobs_list,\n meta={'_type': _type.xpath('./text()').extract()}\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n jobs = sel.xpath('//ul[@class=\"job-vacancies-listing\"]/li')\n for job in jobs:\n job_url = job.xpath('./h2/a/@href').extract()\n if job_url:\n job_url = urljoin(response.url, job_url[0])\n meta = {\n 'jobtype': response.meta.get('_type'),\n 'title': job.xpath('./h2/a/text()').extract(),\n 'loc': job.xpath(\n './/h3[text()=\"Location: \"]/following-sibling::p[1]/text()'\n ).extract(),\n 'sal': job.xpath(\n './/h3[text()=\"Salary: \"]/following-sibling::p[1]/text()'\n ).extract(),\n }\n yield Request(\n job_url, callback=self.parse_job_callback(), meta=meta\n )\n\n next_url = sel.xpath(\n '//a[text()=\"%s\"]/@href' % unicode('next ›', 'utf-8')\n ).extract()\n if next_url:\n next_url = urljoin(response.url, next_url[0])\n yield Request(\n next_url, callback=self.parse_jobs_list,\n meta={'_type': response.meta.get('_type')}\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n if 'other' in response.meta.get('loc', '') or 'Other' in response.meta.get('loc'):\n loader.add_xpath('location', '//p[@class=\"field-area\"]/text()')\n else:\n loader.add_value('location', response.meta.get('loc'))\n\n loader.add_value('location', response.meta.get('loc'))\n\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('jobtype', response.meta.get('jobtype'))\n loader.add_value('baseSalary', response.meta.get('sal'))\n loader.add_value(\n 'referencenumber', response.url,\n Prefix('%s-' % self.name), re=self.ref_re\n )\n\n loader.add_xpath(\n 'description',\n [\n '//h3[contains(text(), \"Key skills\")]',\n '//h3[contains(text(), \"Key skills\")]/following-sibling::node()',\n ]\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/deerfoot.py","file_name":"deerfoot.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"536337078","text":"from flask import Flask, render_template, url_for, request, flash, redirect, escape, session, jsonify\nfrom flask_session.__init__ import Session\nfrom flask_mysqldb import MySQL\nfrom flask_sqlalchemy import SQLAlchemy\nfrom Forms import registroAcademicoForm, loginForm, registroProyectoForm\nfrom flask_migrate import Migrate\napp = Flask(__name__)\n\n\n# MYSQL\napp.config['MYSQL_pyHOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASS'] = ''\napp.config['MYSQL_DB'] = 'unacar'\nmysql = MySQL(app)\n\n# SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://usuario:password@localhost/unacar'\napp.config['SECRET_KEY'] = 'SJIAJ8949A!is0-r{-.,ds'\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\n# SESION\napp.secret_key = 'llavesukisecreta'\n\n\nclass Posgrados(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n facultad = db.Column(db.String(50))\n nombrePosgrado = db.Column(db.String(50))\n\n\nclass Programas_educativos(db.Model):\n nombre = db.Column(db.String(50), primary_key=True)\n facultad = db.Column(db.String(50))\n\n\n@app.route('/')\ndef home():\n if 'numEmpleado' in session:\n if session.get('tipoCuenta') == 0:\n return redirect(url_for('profesor'))\n else:\n return redirect(url_for('admin'))\n else:\n return render_template('home.html')\n\n\n@app.route('/profesor')\ndef profesor():\n if 'numEmpleado' in session:\n if session.get('tipoCuenta') == 1:\n return redirect(url_for('admin'))\n else:\n return render_template('profesor.html')\n else:\n return redirect(url_for('home'))\n\n\n@app.route('/admin')\ndef admin():\n if 'numEmpleado' in session:\n if session.get('tipoCuenta') == 1:\n return render_template('admin.html')\n else:\n return redirect(url_for('profesor'))\n else:\n return redirect(url_for('home'))\n\n\n@app.route('/posgrado/')\ndef posgrado(facultad):\n posgrados = Posgrados.query.filter_by(facultad=facultad).all()\n\n posgradoArray = []\n\n for posgrado in posgrados:\n posgradoObj = {}\n posgradoObj['nombrePosgrado'] = posgrado.nombrePosgrado\n posgradoArray.append(posgradoObj)\n\n return jsonify({'posgrados': posgradoArray})\n\n\n@app.route('/programaEducativo/')\ndef programaEducativo(facultad):\n programasEducativos = Programas_educativos.query.filter_by(\n facultad=facultad).all()\n\n programaEducativoArray = []\n\n for programaEducativo in programasEducativos:\n programaEducativoObj = {}\n programaEducativoObj['nombre'] = programaEducativo.nombre\n programaEducativoArray.append(programaEducativoObj)\n\n return jsonify({'programasEducativos': programaEducativoArray})\n\n\n# MultiStep\n@app.route(\"/registroDatos\", methods=['get', 'post'])\ndef registroDatos():\n form = registroAcademicoForm()\n if 'numEmpleado' in session:\n return render_template(\"random1.html\", form=form)\n else:\n flash('Tienes que estar logeado', 'danger')\n return redirect(url_for('home'))\n\n\n@app.route(\"/registroDatos2\", methods=['get', 'post'])\ndef registroDatos2():\n if request.method == 'POST':\n form = registroAcademicoForm()\n numEmpleado = form.numEmpleado.data\n nombre = form.nombre.data\n facultad = form.facultad.data\n programasEducativos = form.programasEducativos.data\n posgrado = form.posgrado.data\n pertenece_prodep = form.pertenece_prodep.data\n vigencia_prodep = form.vigencia_prodep.data\n programasEducativos = form.programasEducativos.data\n pertenece_sni = form.pertenece_sni.data\n nivelSNI = form.nivelSNI.data\n vigencia_SNI = form.vigencia_SNI.data\n session['pertenece_prodep'] = form.pertenece_prodep.data\n session['pertenece_sni'] = form.pertenece_sni.data\n return render_template(\n \"random2.html\",\n form=form,\n numEmpleado=numEmpleado,\n nombre=nombre,\n facultad=facultad,\n programasEducativos=programasEducativos,\n posgrado=posgrado,\n pertenece_prodep=pertenece_prodep,\n vigencia_prodep=vigencia_prodep,\n pertenece_sni=pertenece_sni,\n nivelSNI=nivelSNI,\n vigencia_SNI=vigencia_SNI)\n else:\n return redirect(url_for('home'))\n\n\n@app.route(\"/guardarDatos\", methods=['get', 'post'])\ndef guardarDatos():\n if request.method == 'POST':\n form = registroAcademicoForm()\n numEmpleado = form.numEmpleado.data\n nombre = form.nombre.data\n facultad = form.facultad.data\n programasEducativos = form.programasEducativos.data\n posgrado = form.posgrado.data\n pertenece_prodep = session.get('pertenece_prodep', None)\n vigencia_prodep = form.vigencia_prodep.data\n pertenece_sni = session.get('pertenece_sni', None)\n nivelSNI = form.nivelSNI.data\n vigencia_SNI = form.vigencia_SNI.data\n grupo_disciplinario = form.grupo_disciplinario.data\n grupo_disciplinario_lgac = form.grupo_disciplinario_lgac.data\n grupo_disciplinario_antiguedad = form.grupo_disciplinario_antiguedad.data\n cuerpo_academico = form.posgrado.data\n cuerpo_academico_lgac = form.cuerpo_academico_lgac.data\n cuerpo_academico_consolidacion = form.cuerpo_academico_consolidacion.data\n cuerpo_academico_obtencion = form.cuerpo_academico_obtencion.data\n nucleo_academico_basico = form.nucleo_academico_basico.data\n nucleo_academico_basico_lgac = form.nucleo_academico_basico_lgac.data\n nucleo_academico_basico_obtencion = form.nucleo_academico_basico_obtencion.data\n # Guardado MYSQL\n cur = mysql.connection.cursor()\n cur.execute(\n 'INSERT INTO academicos (numEmpleado, nombre, facultad, programa_educativo, posgrado, pertenece_prodep, vigencia_prodep, pertenece_sni, vigencia_sni, nivel_sni, grupo_disciplinario, grupo_disciplinario_lgac, grupo_disciplinario_antiguedad, cuerpo_academico, cuerpo_academico_lgac, cuerpo_academico_consolidacion, cuerpo_academico_obtencion, nucleo_academico_basico, nucleo_academico_basico_lgac, nucleo_academico_basico_obtencion)\tVALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (numEmpleado,\n nombre,\n facultad,\n programasEducativos,\n posgrado,\n pertenece_prodep,\n vigencia_prodep,\n pertenece_sni,\n vigencia_SNI,\n nivelSNI,\n grupo_disciplinario,\n grupo_disciplinario_lgac,\n grupo_disciplinario_antiguedad,\n cuerpo_academico,\n cuerpo_academico_lgac,\n cuerpo_academico_consolidacion,\n cuerpo_academico_obtencion,\n posgrado,\n nucleo_academico_basico_lgac,\n nucleo_academico_basico_obtencion))\n mysql.connection.commit()\n flash('Registrado Correctamente', 'success')\n return redirect(url_for('home'))\n else:\n return redirect(url_for('home'))\n return render_template(\"random3.html\", form=form)\n\n\n# Multistep\n\n\n@app.route('/registro')\ndef registro():\n if 'numEmpleado' in session:\n return redirect(url_for('home'))\n else:\n return render_template('registro.html')\n\n\n@app.route('/registrarEmpleado', methods=['POST'])\ndef registrarEmpleado():\n if request.method == 'POST':\n numEmpleado = request.form['numEmpleado']\n nombre = request.form['nombre']\n correo = request.form['correo']\n password = request.form['password']\n password2 = request.form['password2']\n if password != password2:\n flash('Las contraseñas no coinciden')\n return render_template('registro.html')\n else:\n cur = mysql.connection.cursor()\n cur.execute(\n 'SELECT * FROM usuarios WHERE numEmpleado = %s' %\n numEmpleado)\n data = cur.fetchall()\n if len(data) == 1:\n flash(\n 'El número de empleado %s ya se encuentra registrado' %\n numEmpleado)\n return redirect(url_for('registro'))\n else:\n cur = mysql.connection.cursor()\n cur.execute(\n 'INSERT INTO usuarios (numEmpleado, nombre, password, correo) VALUES (%s, %s, %s, %s)',\n (numEmpleado,\n nombre,\n password,\n correo))\n mysql.connection.commit()\n flash('Registrado Correctamente')\n return redirect(url_for('registro'))\n\n return render_template('registro.html')\n\n\n@app.route('/registroDatosAcademicos', methods=['GET', 'POST'])\ndef registroDatosAcademicos():\n if 'numEmpleado' in session:\n form = registroAcademicoForm()\n if request.method == 'POST':\n print(form.programasEducativos.data)\n numEmpleado = form.numEmpleado.data\n nombre = form.nombre.data\n facultad = form.facultad.data\n programasEducativos = form.programasEducativos.data\n posgrado = form.posgrado.data\n pertenece_prodep = session['pertenece_prodep']\n vigencia_prodep = form.vigencia_prodep.data\n pertenece_sni = session['pertenece_sni']\n print(pertenece_prodep)\n print(pertenece_sni)\n nivelSNI = form.nivelSNI.data\n vigencia_SNI = form.vigencia_SNI.data\n grupo_disciplinario = form.grupo_disciplinario.data\n grupo_disciplinario_lgac = form.grupo_disciplinario_lgac.data\n grupo_disciplinario_antiguedad = form.grupo_disciplinario_antiguedad.data\n cuerpo_academico = form.cuerpo_academico.data\n cuerpo_academico_lgac = form.cuerpo_academico_lgac.data\n cuerpo_academico_consolidacion = form.cuerpo_academico_consolidacion.data\n cuerpo_academico_obtencion = form.cuerpo_academico_obtencion.data\n nucleo_academico_basico = form.nucleo_academico_basico.data\n nucleo_academico_basico_lgac = form.nucleo_academico_basico_lgac.data\n nucleo_academico_basico_obtencion = form.nucleo_academico_basico_obtencion.data\n cur = mysql.connection.cursor()\n cur.execute(\n 'INSERT INTO academicos (numEmpleado, nombre, facultad, programa_educativo, posgrado, pertenece_prodep, vigencia_prodep, pertenece_sni, vigencia_sni, nivel_sni, grupo_disciplinario, grupo_disciplinario_lgac, grupo_disciplinario_antiguedad, cuerpo_academico, cuerpo_academico_lgac, cuerpo_academico_consolidacion, cuerpo_academico_obtencion, nucleo_academico_basico, nucleo_academico_basico_lgac, nucleo_academico_basico_obtencion)\tVALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (numEmpleado,\n nombre,\n facultad,\n programasEducativos,\n posgrado,\n pertenece_prodep,\n vigencia_prodep,\n pertenece_sni,\n vigencia_SNI,\n nivelSNI,\n grupo_disciplinario,\n grupo_disciplinario_lgac,\n grupo_disciplinario_antiguedad,\n cuerpo_academico,\n cuerpo_academico_lgac,\n cuerpo_academico_consolidacion,\n cuerpo_academico_obtencion,\n nucleo_academico_basico,\n nucleo_academico_basico_lgac,\n nucleo_academico_basico_obtencion))\n mysql.connection.commit()\n flash(\n 'Tus datos han sido registrados de manera satisfactoria',\n 'success')\n return render_template('registroDatosAcademicos.html', form=form)\n flash(\"Tus datos han sido guardados\", 'success')\n return render_template('registroDatosAcademicos.html', form=form)\n return render_template('registroDatosAcademicos.html', form=form)\n return redirect(url_for('home'))\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n return render_template('500.html'), 500\n\n\n@app.route('/checkDatosAcademicos')\ndef checkDatosAcademicos():\n if 'numEmpleado' in session:\n cur = mysql.connection.cursor()\n cur.execute(\n 'SELECT * FROM usuarios WHERE numEmpleado = %s AND password = %s',\n (numEmpleado,\n password))\n datosProfesor = cur.fetchall()\n\n\n@app.route('/logout')\ndef logout():\n if 'numEmpleado' in session:\n # Borrar la sesión\n session.pop('numEmpleado', None)\n session.pop('tipoCuenta', None)\n session.pop('nombre', None)\n session.pop('_flashes', None) # Borra los flashes(mensajes) restantes\n flash('Has cerrado sesión.', 'info')\n\n return redirect(url_for('home'))\n\n# MultiStep\n@app.route(\"/registroProyectos\", methods=['get', 'post'])\ndef registroProyectos():\n if 'numEmpleado' in session:\n form = registroProyectoForm()\n if request.method == 'POST':\n nombreProyecto = form.nombreProyecto.data\n descripcionProyecto = form.descripcionProyecto.data\n aplicacionesProyecto = form.aplicacionesProyecto.data\n nivelTRL = request.form.get(\"nivelTRL\")\n # Guardado MYSQL\n try:\n cur = mysql.connection.cursor()\n cur.execute(\n 'INSERT INTO proyectos (ProyectoID, NombreProyecto, Descripcion, AplicacionesProyecto, NivelTRL)\tVALUES (%s, %s, %s, %s, %s)',\n (session.get('numEmpleado'),\n nombreProyecto,\n descripcionProyecto,\n aplicacionesProyecto,\n nivelTRL))\n mysql.connection.commit()\n flash(\n 'Tu proyecto '+str(form.nombreProyecto.data.lower())+' ha sido registrado satisfactioramente',\n 'success')\n return render_template(\"registroProyectos.html\", form=form)\n except Exception as e:\n flash('Error: ' + str(e), 'danger')\n return render_template(\"registroProyectos.html\", form=form)\n return render_template(\"registroProyectos.html\", form=form)\n else:\n flash('Tienes que estar logeado', 'danger')\n return redirect(url_for('home'))\n\n\n@app.route('/login', methods=['POST', 'GET'])\ndef login():\n error = None\n if 'numEmpleado' in session:\n return redirect(url_for('home'))\n if request.method == 'POST':\n numEmpleado = request.form['numEmpleado']\n password = request.form['password']\n cur = mysql.connection.cursor()\n cur.execute(\n 'SELECT * FROM usuarios WHERE numEmpleado = %s AND password = %s',\n (numEmpleado,\n password))\n datosProfesor = cur.fetchall()\n if len(datosProfesor) == 0:\n flash('El usuario o contraseña son incorrectos', 'danger')\n return redirect(url_for('home'))\n tipoCuenta = datosProfesor[0][4]\n print(tipoCuenta)\n if tipoCuenta == 1:\n # Se crea la sesión, guardamos datos en variables\n session['loggedin'] = True\n session['numEmpleado'] = datosProfesor[0][0]\n session['nombre'] = datosProfesor[0][1]\n session['tipoCuenta'] = tipoCuenta\n # Redirect to home page\n print(\"Cargando admin page\")\n return redirect(url_for('admin'))\n else:\n # Se crea la sesión, guardamos datos en variables\n session['loggedin'] = True\n session['numEmpleado'] = datosProfesor[0][0]\n session['nombre'] = datosProfesor[0][1]\n session['tipoCuenta'] = tipoCuenta\n # Redirect to home page\n return redirect(url_for('profesor'))\n\n@app.route('/proyectos')\ndef proyectos():\n return 'Acerca de'\n\n@app.route('/acerca')\ndef acerca():\n return 'Acerca de'\n\n\n@app.route('/get_prodep_toggled_status')\ndef toggled_prodep_status():\n current_status = request.args.get('status')\n return 'Sí soy parte del PRODEP' if current_status == 'No soy parte del PRODEP' else 'No soy parte del PRODEP'\n\n\n@app.route('/get_SNI_toggled_status')\ndef toggled_sni_status():\n current_status = request.args.get('status')\n return 'Sí soy parte del SNI' if current_status == 'No soy parte del SNI' else 'No soy parte del SNI'\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"index - copia.py","file_name":"index - copia.py","file_ext":"py","file_size_in_byte":16826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"1019786","text":"# NOTE: THIS SOLUTION IS NOT COMPLETE - COULD NOT FIGURE OUT THE CORRECT WAY TO WEAVE THE LISTS TOGETHER\nclass Node:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef main():\n # two = Node(2)\n # one = Node(1)\n # three = Node(3)\n\n # two.left = one\n # two.right = three\n\n # for x in get_permutation(two):\n # print(x)\n\n# 4\n# / \\\n# 2 6\n# / \\\n # 5 8\n four = Node(4)\n two = Node(2)\n six = Node(6)\n five = Node(5)\n eight = Node(8)\n\n four.left = two\n four.right = six\n six.left = five\n six.right = eight\n\n for x in get_permutation(four):\n print(x)\n\ndef get_permutation(root):\n if root == None:\n array = []\n return array\n if not root.left and not root.right:\n array = []\n array.append(root.value)\n return array\n left = get_permutation(root.left)\n right = get_permutation(root.right)\n\n results = []\n for x in range(len(left)):\n for y in range(len(right)):\n results.append([root.value] + left[:x] + right[:y] + left[x:] + right[y:])\n results.append([root.value] + right[:y] + left[:x] + right[y:] + left[x:])\n return results\n\n\nmain()","sub_path":"4-trees-and-graphs/4.9/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"417168216","text":"\"\"\"NTopo.\n\nUsage:\n run.py list_problems\n run.py list_problems_space\n run.py train_config \n run.py train [--volume_ratio=0.5] [--lr_sim=3e-4] [--lr_opt=3e-4]\n [--save_interval=5] [--use_mmse=1] [--filter=sensitivity] [--filter_radius=2.0]\n [--vol_penalty_strength=10]\n [--use_oc=1] [--n_opt_iterations=1000] [--n_sim_iterations=1000] [--n_opt_batches=50]\n run.py evaluate [--n_samples=]\n [--n_samples_compliance=]\n run.py train_space_config \n run.py train_space [--volume_ratio=0.5] [--lr_sim=3e-4] [--lr_opt=3e-4]\n [--save_interval=5] [--filter=sensitivity] [--filter_radius=2.0] [--use_oc=1]\n [--n_opt_iterations=1000] [--n_sim_iterations=1000] [--n_opt_batches=50]\n [--n_q_samples=5]\n run.py evaluate_space [--n_samples=]\n [--n_samples_compliance=] [--n_q_samples=]\n run.py --version\n run.py --help\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n --vol_penalty_strength= Penalty weight when not using OC [default: 10]\n --volume_ratio= Target volume ratio [default: 0.5]\n --lr_sim= Learning rate for the displacement field [default: 3e-4]\n --lr_opt= Learning rate for the density field [default: 3e-4]\n --save_interval= Save interval during optimization [default: 5]\n --use_mmse= Whether to use mmse for training [default: 1]\n --filter= Filter to use, either none, sensitivity [default: sensitivity]\n --filter_radius= Filter radius [default: 2.0]\n --use_oc= Use optimality criterion, either 0 or 1 [default: 1]\n --n_opt_iterations= Number of optimization iterations for outer loop [default: 1000]\n --n_sim_iterations= Number of inner simulation steps [default: 1000]\n --n_opt_batches= Number of batches for updating the density network [default: 50]\n --n_q_samples= Number of samples of q [default: 5]\n --n_samples= Number of samples for creating image [default: 30000]\n --n_samples_compliance= Number of samples when evaluating compliance [default: 30000]\n\"\"\"\n\nimport os\nfrom importlib import reload\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom docopt import docopt\nimport tensorflow as tf\n\nfrom ntopo.problems import problems, space_problems, get_problem_by_name, get_space_problem_by_name\nfrom ntopo.models import DensityModel, DispModel\nfrom ntopo.train import train_mmse, train_non_mmse, train_mmse_space\nfrom ntopo.utils import (\n set_random_seed, get_sample_generator, get_default_sample_counts,\n write_to_json_file, read_from_json_file, write_to_file, get_grid_centers\n)\nfrom ntopo.render import predict_densities_image_2d, save_densities_to_file\nfrom ntopo.fem_sim import estimate_compliance\n\nDEFAULT_N_SIM_SAMPLES_2D = 150*50\nDEFAULT_N_OPT_SAMPLES_2D = 150*50\nDEFAULT_N_SIM_SAMPLES_3D = 80*40*20\nDEFAULT_N_OPT_SAMPLES_3D = 80*40*20\n\ndef get_new_idx():\n \"\"\"\n returns new index for storing result based on the counter.txt file\n \"\"\"\n count = 0\n counter_file = 'counter.txt'\n if os.path.exists(counter_file):\n with open(counter_file, 'r', encoding='utf8') as file_object:\n count = int(file_object.read().splitlines()[-1])\n with open(counter_file, 'w+', encoding='utf8') as file_object:\n file_object.write(str(count+1))\n return count\n\n\ndef create_new_save_folder(name_format):\n \"\"\"\n creates new folder to store result and returns the path of the folder\n \"\"\"\n\n results_folder = 'results'\n\n new_idx = get_new_idx()\n folder_name = name_format.format(idx=new_idx)\n current_dir = os.path.dirname(os.path.realpath(__file__))\n new_path = os.path.join(current_dir, results_folder, folder_name)\n if not os.path.exists(os.path.join(current_dir, results_folder)):\n os.mkdir(os.path.join(current_dir, results_folder))\n if not os.path.exists(new_path):\n os.mkdir(new_path)\n return new_path\n\ndef instantiate_optimizer(config):\n return tf.keras.optimizers.get(config)\n\ndef train_config_single(config):\n set_random_seed(config['seed'])\n\n problem_name = config['problem_name']\n\n problem = get_problem_by_name(problem_name)\n problem.init()\n\n opt_disp = instantiate_optimizer(config['opt_disp'])\n opt_density = instantiate_optimizer(config['opt_density'])\n\n optimizer_name = type(opt_density).__name__\n\n save_path = create_new_save_folder(\n name_format=problem_name + '-' + optimizer_name + '-{idx}_vol_' + str(config['volume_ratio']))\n\n write_to_json_file(config, os.path.join(save_path, \"config.txt\"))\n\n disp_model = DispModel(input_domain=problem.domain, dim=problem.dim,\n bc=problem.bc, features=config['disp_model_features_config'], model=config['disp_model_config'])\n density_model = DensityModel(\n input_domain=problem.domain,\n dim=problem.dim,\n volume_ratio=config['volume_ratio'],\n constraint=problem.density_constraint,\n features=config['density_model_features_config'],\n model=config['density_model_config']\n )\n\n print('n_sim_samples ', config['n_sim_samples'])\n print('n_opt_samples ', config['n_opt_samples'])\n sim_sample_generator = get_sample_generator(problem.domain, config['n_sim_samples'])\n opt_sample_generator = get_sample_generator(problem.domain, config['n_opt_samples'])\n\n if config['use_mmse'] == 1:\n train_mmse(\n problem=problem, disp_model=disp_model,\n density_model=density_model, opt_disp=opt_disp, opt_density=opt_density,\n opt_sample_generator=opt_sample_generator,\n sim_sample_generator=sim_sample_generator,\n n_opt_samples=config['n_opt_samples'],\n vol_penalty_strength=config['vol_penalty_strength'],\n target_volume_ratio=config['volume_ratio'],\n save_path=save_path,\n filter=config['filter'],\n filter_radius=config['filter_radius'],\n use_oc=config['use_oc'],\n save_interval=config['save_interval'],\n n_opt_iterations=config['n_opt_iterations'],\n n_sim_iterations=config['n_sim_iterations'],\n n_opt_batches=config['n_opt_batches'],\n oc_config=config['oc']\n )\n else:\n train_non_mmse(problem, disp_model, density_model, opt_disp, opt_density,\n opt_sample_generator, sim_sample_generator,\n vol_penalty_strength=config['vol_penalty_strength'],\n target_volume_ratio=config['volume_ratio'],\n save_path=save_path,\n save_interval=config['save_interval'],\n n_opt_iterations=config['n_opt_iterations'],\n n_sim_iterations=config['n_sim_iterations'],\n )\n\ndef transfer_arguments_to_config(arguments, config):\n config['volume_ratio'] = float(arguments['--volume_ratio'])\n config['filter'] = arguments['--filter']\n config['filter_radius'] = float(arguments['--filter_radius'])\n config['save_interval'] = int(arguments['--save_interval'])\n config['vol_penalty_strength'] = float(arguments['--vol_penalty_strength'])\n config['use_mmse'] = int(arguments['--use_mmse'])\n config['n_opt_iterations'] = int(arguments['--n_opt_iterations'])\n config['n_sim_iterations'] = int(arguments['--n_sim_iterations'])\n config['n_opt_batches'] = int(arguments['--n_opt_batches'])\n config['n_q_samples'] = int(arguments['--n_q_samples'])\n config['use_oc'] = arguments['--use_oc'] != '0'\n config['opt_disp'] = {\n 'class_name': 'Adam',\n 'config': {\n 'learning_rate': float(arguments['--lr_sim']),\n 'beta_2': 0.99,\n }\n }\n config['opt_density'] = {\n 'class_name': 'Adam',\n 'config': {\n 'learning_rate': float(arguments['--lr_opt']),\n 'beta_1': 0.8,\n 'beta_2': 0.9,\n }\n }\n\ndef train_single(arguments):\n \"\"\"\n generates default config from arguments and runs it\n \"\"\"\n\n problem_name = arguments['']\n\n problem = get_problem_by_name(problem_name)\n problem.init()\n\n config = {\n 'problem_name': problem_name,\n 'seed': 42,\n 'oc': {\n 'max_move': 0.2,\n 'damping_parameter': 0.5\n }\n }\n\n omega0 = 60.0\n if problem.dim == 2:\n n_hidden = 60\n n_sim_samples = get_default_sample_counts(problem.domain, DEFAULT_N_SIM_SAMPLES_2D)\n n_opt_samples = get_default_sample_counts(problem.domain, DEFAULT_N_OPT_SAMPLES_2D)\n else:\n n_hidden = 180\n n_sim_samples = get_default_sample_counts(problem.domain, DEFAULT_N_SIM_SAMPLES_3D)\n n_opt_samples = get_default_sample_counts(problem.domain, DEFAULT_N_OPT_SAMPLES_3D)\n\n features_config = {'class_name': 'ConcatSineFeatures',\n 'config': {'n_input': problem.dim}}\n config['disp_model_features_config'] = features_config\n config['disp_model_config'] = {'class_name': 'DenseSIRENModel', 'config':\n {'n_input': 2*problem.dim, 'n_output': problem.dim, 'n_hidden': n_hidden, 'last_layer_init_scale': 1e-3, 'omega0': omega0}}\n config['density_model_features_config'] = features_config\n config['density_model_config'] = {'class_name': 'DenseSIRENModel', 'config': {\n 'n_input': 2*problem.dim, 'n_output': 1, 'n_hidden': n_hidden, 'last_layer_init_scale': 1e-3, 'omega0': omega0}}\n\n transfer_arguments_to_config(arguments, config)\n\n config['n_sim_samples'] = n_sim_samples.copy()\n config['n_opt_samples'] = n_opt_samples.copy()\n\n train_config_single(config)\n\n\ndef evaluate_single(arguments):\n\n set_random_seed(42)\n\n folder = arguments['']\n weights_name = arguments['']\n\n config = read_from_json_file(os.path.join(folder, \"config.txt\"))\n\n problem_name = config['problem_name']\n problem = get_problem_by_name(problem_name)\n assert problem.dim != 3, \"not implemented\"\n density_model = DensityModel.load_from_config_file(\n os.path.join(folder, \"density_model_config.json\"))\n density_model.load_weights(os.path.join(\n folder, weights_name))\n\n save_path = create_new_save_folder(\n name_format='evaluation-{idx}-' + problem_name)\n\n n_samples = int(arguments['--n_samples'])\n n_samples_xy = get_default_sample_counts(problem.domain, n_samples)\n print('n_samples ', n_samples_xy)\n\n save_prefix = ''\n save_postfix = ''\n filename = os.path.join(save_path, save_prefix +\n 'density' + save_postfix + '.png')\n\n densities_im, _ = predict_densities_image_2d(density_model,\n domain=problem.domain, mirror=problem.mirror, n_samples=n_samples_xy)\n save_densities_to_file(densities_im, filename)\n\n # need to evaluate seperatly as estimate_compliance and fem bcs expects not mirrored densities\n n_samples_compliance = int(arguments['--n_samples_compliance'])\n n_samples_compliance_xy = get_default_sample_counts(problem.domain, n_samples_compliance)\n print('n_samples_compliance_xy ', n_samples_compliance_xy)\n densities_comp, _ = predict_densities_image_2d(density_model,\n domain=problem.domain, mirror=[False, False], n_samples=n_samples_compliance_xy)\n filename = os.path.join(save_path, save_prefix +\n 'density_comp' + save_postfix + '.png')\n save_densities_to_file(densities_comp, filename)\n compliance = estimate_compliance(problem, densities_comp, save_path, save_postfix)\n\n volume_ratio_estimate = np.mean(densities_im)\n volume_ratio = config['volume_ratio']\n volume_perc_error = 100.0 * abs(volume_ratio_estimate - volume_ratio)/volume_ratio\n print('Compliance: ', compliance)\n print('Volume ratio estimate: ', volume_ratio_estimate)\n print('Volume perc. error: ', volume_perc_error, '%')\n\n data = {\n 'n_samples': n_samples_xy,\n 'volume_ratio_estimate': volume_ratio_estimate.item(),\n 'volume_perc_error': volume_perc_error.item(),\n 'n_samples_compliance': n_samples_compliance_xy,\n 'compliance': compliance\n }\n filename = os.path.join(save_path, 'data.json')\n write_to_json_file(data, filename)\n\ndef train_config_space(config):\n\n set_random_seed(config['seed'])\n\n problem_name = config['problem_name']\n\n problem = get_space_problem_by_name(problem_name)\n problem.init()\n\n opt_disp = instantiate_optimizer(config['opt_disp'])\n opt_density = instantiate_optimizer(config['opt_density'])\n optimizer_name = type(opt_density).__name__\n\n save_path = create_new_save_folder(\n name_format=problem_name + '-' + optimizer_name + '-{idx}_vol_' + str(config['volume_ratio'])\n )\n\n write_to_json_file(config, os.path.join(save_path, \"config.txt\"))\n\n disp_model_config = {\n 'input_domain': config['input_domain'], 'dim': problem.dim,\n 'bc': problem.bc, 'features': config['disp_model_features_config'], 'model': config['disp_sub_model_config']\n }\n disp_model = DispModel(**disp_model_config)\n density_model = DensityModel(\n input_domain=config['input_domain'],\n dim=problem.dim, volume_ratio=config['volume_ratio'],\n constraint=problem.density_constraint,\n features=config['density_model_features_config'],\n model=config['density_model_config'],\n volume_ratio_q_idx=problem.volume_ratio_q_idx\n )\n\n opt_sample_generator = get_sample_generator(problem.domain, config['n_opt_samples'])\n\n train_mmse_space(problem, disp_model, density_model, opt_disp, opt_density,\n config['n_sim_samples'], config['n_opt_samples'],\n opt_sample_generator,\n vol_penalty_strength=config['vol_penalty_strength'],\n target_volume_ratio=config['volume_ratio'],\n save_path=save_path,\n filter=config['filter'],\n filter_radius=config['filter_radius'],\n use_oc=config['use_oc'],\n save_interval=config['save_interval'],\n n_opt_iterations=config['n_opt_iterations'],\n n_sim_iterations=config['n_sim_iterations'],\n n_opt_batches=config['n_opt_batches'],\n n_q_samples=config['n_q_samples'],\n oc_config=config['oc']\n )\n\ndef train_space(arguments):\n \"\"\"\n generates default configuration and then also runs it\n \"\"\"\n\n problem_name = arguments['']\n\n problem = get_space_problem_by_name(problem_name)\n problem.init()\n\n n_input = problem.dim + problem.q_dim\n\n if problem.dim == 2:\n n_sim_samples = get_default_sample_counts(problem.domain, DEFAULT_N_SIM_SAMPLES_2D)\n n_opt_samples = get_default_sample_counts(problem.domain, DEFAULT_N_OPT_SAMPLES_2D)\n else:\n n_sim_samples = get_default_sample_counts(problem.domain, DEFAULT_N_SIM_SAMPLES_3D)\n n_opt_samples = get_default_sample_counts(problem.domain, DEFAULT_N_OPT_SAMPLES_3D)\n\n n_hidden_disp = 256\n n_hidden_density = 256\n omega0 = 60.0\n\n config = {\n 'problem_name': problem_name,\n 'seed': 42,\n 'oc': {\n 'max_move': 0.2,\n 'damping_parameter': 0.5\n }\n }\n\n transfer_arguments_to_config(arguments, config)\n\n config['input_domain'] = np.concatenate((problem.domain, problem.q_domain), axis=0).tolist()\n\n features_config = {\n 'class_name': 'ConcatSineFeatures',\n 'config': {'n_input': n_input}\n }\n config['disp_model_features_config'] = features_config\n config['disp_sub_model_config'] = {\n 'class_name': 'DenseSIRENModel', 'config': {'n_input': 2*n_input,\n 'n_output': problem.dim, 'n_hidden': n_hidden_disp, 'last_layer_init_scale': 1e-3, 'omega0': omega0}\n }\n config['density_model_features_config'] = features_config\n config['density_model_config'] = {\n 'class_name': 'DenseSIRENModel', 'config': {'n_input': 2*n_input,\n 'n_output': 1, 'n_hidden': n_hidden_density, 'last_layer_init_scale': 1e-3, 'omega0': omega0}\n }\n\n assert config['disp_model_features_config']['config']['n_input'] == (len(config['input_domain'])//2)\n assert config['density_model_features_config']['config']['n_input'] == (len(config['input_domain'])//2)\n\n config['n_sim_samples'] = n_sim_samples.copy()\n config['n_opt_samples'] = n_opt_samples.copy()\n\n train_config_space(config)\n\n\ndef evaluate_space(arguments):\n\n set_random_seed(42)\n\n folder = arguments['']\n weights_name = arguments['']\n\n config = read_from_json_file(os.path.join(folder, \"config.txt\"))\n problem_name = config['problem_name']\n\n save_path = create_new_save_folder(\n name_format='evaluation-{idx}-' + problem_name)\n write_to_json_file(arguments, os.path.join(save_path, \"arguments.txt\"))\n\n problem = get_space_problem_by_name(problem_name)\n density_model = DensityModel.load_from_config_file(\n os.path.join(folder, \"density_model_config.json\"))\n density_model.load_weights(os.path.join(\n folder, weights_name))\n\n n_samples = int(arguments['--n_samples'])\n n_q_samples = int(arguments['--n_q_samples'])\n n_samples_compliance = int(arguments['--n_samples_compliance'])\n [n_samples_compliance_x, n_samples_compliance_y] = get_default_sample_counts(problem.domain, n_samples_compliance)\n print('n_samples_compliance', [n_samples_compliance_x, n_samples_compliance_y])\n\n # even width and height is required for some video encoders\n n_samples_xy = get_default_sample_counts(problem.domain, n_samples, even = True)\n qs = problem.get_plot_samples(n_q_samples)\n filenames = []\n volume_ratio_estimates = []\n compliances = []\n estimate_compliances = True\n save_prefix=''\n for i in range(len(qs)):\n q = qs[i]\n assert np.size(q) == 1\n q0 = q.item()\n save_postfix = f'-q={q0:.6f}'\n\n print('Processing ', i, '/', len(qs) - 1)\n filename = os.path.join(save_path, save_prefix +\n 'density' + save_postfix + '.png')\n densities_im, _ = predict_densities_image_2d(density_model.get_model_partial_q(q),\n domain=problem.domain, mirror=problem.mirror, n_samples=n_samples_xy)\n\n save_densities_to_file(densities_im, filename)\n volume_ratio_estimate = np.mean(densities_im)\n volume_ratio_estimates.append(volume_ratio_estimate.item())\n filenames.append(filename)\n\n if estimate_compliances:\n positions_comp = get_grid_centers(problem.domain, [n_samples_compliance_x, n_samples_compliance_y])\n densities_comp = density_model.get_model_partial_q(q).predict(positions_comp, batch_size=1024)\n densities_comp = np.reshape(densities_comp, (n_samples_compliance_y, n_samples_compliance_x))\n compliance = estimate_compliance(problem, densities_comp, save_path, save_postfix, problem_bc_args={ 'q': q })\n compliances.append(compliance)\n\n qs = np.concatenate(qs, axis=0)\n data = { 'qs': qs.tolist(), 'volume_ratio_estimates': volume_ratio_estimates }\n if estimate_compliances:\n data['compliances'] = compliances\n filename = os.path.join(save_path, 'data.json')\n write_to_json_file(data, filename)\n\n assert qs.shape[1] == 1 # code assumes 1dim q for now\n qs = qs.squeeze()\n if estimate_compliances:\n fig, ax = plt.subplots()\n ax.plot(qs, compliances)\n ax.set_xlabel('Q')\n fig.savefig(os.path.join(save_path, 'compliances.png'))\n plt.close(fig)\n\n volume_ratio_estimates = np.array(volume_ratio_estimates, dtype=np.float32)\n\n fig, ax = plt.subplots()\n ax.plot(qs, volume_ratio_estimates)\n ax.set_xlabel('Q')\n ax.set_ylabel('Volume ratio')\n fig.savefig(os.path.join(save_path, 'volume_ratio_estimates.png'))\n plt.close(fig)\n\n if problem.volume_ratio_q_idx != -1:\n volume_ratio_rel_error = abs(volume_ratio_estimates - qs) / qs\n else:\n volume_ratio_rel_error = abs(volume_ratio_estimates - config['volume_ratio']) / config['volume_ratio']\n fig, ax = plt.subplots()\n ax.plot(qs, volume_ratio_rel_error * 100.0)\n ax.set_xlabel('Q')\n ax.set_ylabel('Volume percentage error')\n fig.savefig(os.path.join(save_path, 'volume_ratio_errors.png'))\n plt.close(fig)\n\n lines = [\n \"file '\" + os.path.split(f)[1] + \"'\" + '\\n' + 'duration 0.03' for f in filenames]\n filenames_str = '\\n'.join(lines)\n write_to_file(filenames_str, os.path.join(save_path, 'filenames.txt'))\n write_to_file('ffmpeg -safe 0 -f concat -i filenames.txt -pix_fmt yuv420p output.mp4',\n os.path.join(save_path, 'make_video.bat'))\n write_to_file('#!/bin/bash\\nffmpeg -safe 0 -f concat -i filenames.txt -pix_fmt yuv420p -f mp4 output.mp4',\n os.path.join(save_path, 'make_video.sh'))\n\n\ndef main():\n arguments = docopt(__doc__, version='NTopo 1.0')\n\n # in the TkAgg backend there is a bug it seems which will run into \"Fail to allocate bitmap\" error\n # so we use a different backend\n # http://matplotlib.1069221.n5.nabble.com/Fail-to-allocate-bitmap-Unable-to-free-colormap-palette-is-still-selected-td13203.html\n reload(matplotlib)\n matplotlib.use('Agg')\n\n if arguments['list_problems']:\n print('Problems:')\n for p in problems:\n print(' ', p.__name__)\n\n elif arguments['list_problems_space']:\n print('Space problems:')\n for p in space_problems:\n print(' ', p.__name__)\n elif arguments['train_config']:\n config = read_from_json_file(arguments[''])\n train_config_single(config)\n elif arguments['train']:\n train_single(arguments)\n elif arguments['evaluate']:\n evaluate_single(arguments)\n elif arguments['train_space_config']:\n config = read_from_json_file(arguments[''])\n train_config_space(config)\n elif arguments['train_space']:\n train_space(arguments)\n elif arguments['evaluate_space']:\n evaluate_space(arguments)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":22244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"316649622","text":"#coding:utf-8\n'''\n@author : chencheng\n@company: topzero.cn\n@date : 20180617\n@brief :\n mfcc -> mel-frequency cepstral coefficients,梅尔频率倒谱系数\n filter banks 滤波bank\n'''\n\nimport numpy as np\nimport scipy.io.wavfile\nimport scipy.fftpack\n\nimport matplotlib.pyplot as plt\n\n\ndef PlotWav(wav):\n plt.plot(range(len(wav)), wav)\n plt.show()\n\n\ndef mfcc(signal, sample_rate):\n ''' Pre-Emphasis, not needed in modern speech processing system '''\n emphasized_signal = signal \n\n ''' Framing '''\n frame_size = 0.025\n frame_stride = 0.01\n frame_length = frame_size * sample_rate\n frame_step = frame_stride * sample_rate\n signal_length = len(emphasized_signal)\n frame_length = int(round(frame_length))\n frame_step = int(round(frame_step))\n\n # Make sure that we have at least 1 frame\n num_frames = int(np.ceil(float(np.abs(signal_length - frame_length)) / frame_step)) \n\n pad_signal_length = num_frames * frame_step + frame_length\n z = np.zeros((pad_signal_length - signal_length))\n # Pad Signal to make sure that all frames have equal number of samples, \n # without truncating any samples from the original signal\n pad_signal = np.append(emphasized_signal, z) \n\n indices = np.tile(np.arange(0, frame_length), (num_frames, 1)) + \\\n np.tile(np.arange(0, num_frames * frame_step, frame_step),\n (frame_length, 1) ).T\n # print(indices)\n frames = pad_signal[indices.astype(np.int32, copy=False)]\n\n ''' window function '''\n print(('before windowing', frames.shape, np.hamming(frame_length).shape))\n frames *= np.hamming(frame_length)\n print(('after windowing', frames.shape))\n\n ''' Fourier-Transform and Power Spectrum '''\n NFFT = 512\n mag_frames = np.absolute(np.fft.rfft(frames, NFFT)) # Magnitude of the FFT\n pow_frames = ((1.0 / NFFT) * ((mag_frames) ** 2)) # Power Spectrum\n print(('power_frames', pow_frames.shape))\n\n ''' Filter Banks '''\n nfilt = 40\n low_freq_mel = 0\n high_freq_mel = (2595 * np.log10(1 + (sample_rate / 2) / 700)) # Convert Hz to Mel\n mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2) # Equally spaced in Mel scale\n hz_points = (700 * (10**(mel_points / 2595) - 1)) # Convert Mel to Hz \n bin = np.floor((NFFT + 1) * hz_points / sample_rate)\n\n fbank = np.zeros((nfilt, int(np.floor(NFFT / 2 + 1))))\n for m in range(1, nfilt + 1):\n f_m_minus = int(bin[m - 1]) # left\n f_m = int(bin[m]) # center\n f_m_plus = int(bin[m + 1]) # right\n\n for k in range(f_m_minus, f_m):\n fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])\n for k in range(f_m, f_m_plus):\n fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])\n print(('fbank', fbank.shape))\n\n filter_banks = np.dot(pow_frames, fbank.T)\n filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks) # Numerical Stability\n filter_banks = 20 * np.log10(filter_banks) # dB\n\n\n ''' MFCC '''\n num_ceps = 12\n mfcc = scipy.fftpack.dct(filter_banks, type=2, axis=1, norm='ortho')[:, 1 : (num_ceps + 1)] # Keep 2-13\n #(nframes, ncoeff) = mfcc.shape\n #n = np.arange(ncoeff)\n #lift = 1 + (cep_lifter / 2) * np.sin(np.pi * n / cep_lifter)\n #mfcc *= lift #*\n\n\n ''' mean normalization '''\n filter_banks -= (np.mean(filter_banks, axis=0) + 1e-8)\n mfcc -= (np.mean(mfcc, axis=0) + 1e-8)\n print(('fiterbanks', filter_banks.shape))\n print(('mfcc', mfcc.shape))\n\n print('# mfcc vs filter-bank!')\n return filter_banks, mfcc \n\n\ndef main():\n ''' setup '''\n wavpath = '/home/chen/myworkspace/gits/Matlab-toolbox-for-DNN-based-speech-separation/premix_data/clean_speech/S_01_01.wav'\n # wavpath = '/home/chen/dataset/speech_commands_v0.01/bed/0a7c2a8d_nohash_0.wav'\n\n sample_rate, signal = scipy.io.wavfile.read(wavpath)\n print(('rate, len, time', sample_rate, len(signal), len(signal)/float(sample_rate)))\n # PlotWav(signal)\n\n mfcc(signal, sample_rate)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mfcc/mfcc.py","file_name":"mfcc.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"283416672","text":"# 직사각형에서 탈출하기\n'''\n점은 지금 (x, y)에 있다. 직사각형의 왼쪽 아래 꼭짓점은 (0, 0)에 있고, 오른쪽 위 꼭짓점은 (w, h)에 있다.\n직사각형의 경계선까지 가는 거리의 최솟값을 구하는 프로그램을 작성하시오.\n\n첫째 줄에 x y w h가 주어진다.\nw와 h는 1,000보다 작거나 같은 자연수이고, x는 1보다 크거나 같고, \nw-1보다 작거나 같은 자연수이고, y는 1보다 크거나 같고, h-1보다 작거나 같은 자연수이다.\n'''\n\n# Python 3.6\ninputstr = input().split(' ')\nx = []\nfor i in inputstr:\n x.append(int(i))\n\ndistance = [x[0], x[1], x[2]-x[0], x[3]-x[1]]\nprint(min(distance))\n","sub_path":"018_Problem_1085.py","file_name":"018_Problem_1085.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"426138297","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport sys\n\ninfile, outfile = sys.argv[1:]\n\n\n# infile = \"/home/chingyuenliu/complex_contact/test.ffdata\"\n\n# outfile = \"/home/chingyuenliu/complex_contact/tax_id_list\"\n\n# In[6]:\n\n\nimport re\n\n\n# In[4]:\n\n\n\"\"\"\nFind the entry names.\nfor example:\ninput: #UniRef100_A0A5A9P0L4 Peptidylprolyl isomerase n=1 Tax=Triplophysa tibetana TaxID=1572043 RepID=A0A5A9P0L4_9TELE\\n\noutput: A0A5A9P0L4\nMechanism: Find the word after UniRef100\n\"\"\"\npattern = re.compile(r'(?:Tax=)(.+)(?: TaxID=)')\n\n\n# In[25]:\n\n\nwith open(infile, 'r') as f:\n IDs = [pattern.findall(_) for _ in f]\nIDs = sorted(set([item for sublist in IDs for item in sublist]))\n\n\n# print('#entries = %d' % len(IDs))\n\n# In[7]:\n\n\nwith open(outfile, 'w') as f: f.write('\\n'.join(IDs) + '\\n')\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# with open(infile, 'r') as f:\n# sentence = f.read()\n\n# pattern = re.compile(r'(?:Tax=)(.+)(?: TaxID=)')\n\n# pattern.findall(sentence)\n\n# sentence\n\n# import sys\n# \n# infile, outfile = sys.argv[1:]\n# \n\n# with open(infile, 'r') as f:\n# IDs = [_.strip() for _ in f]\n\n# import urllib.parse\n# import urllib.request\n\n# url = 'https://www.uniprot.org/uploadlists/'\n\n# params = {\n# 'from': 'UPARC',\n# 'to': 'ACC',\n# 'format': 'tab',\n# 'query': ''\n# }\n# \n# for ID in IDs:\n# if ID.startswith(\"UPI\"):\n# params[\"query\"] = ID\n# data = urllib.parse.urlencode(params)\n# data = data.encode('utf-8')\n# req = urllib.request.Request(url, data)\n# with urllib.request.urlopen(req) as f:\n# response = f.read()\n# print(response.decode('utf-8'))\n\n# uni_list = [ID for ID in IDs if not ID.startswith(\"UPI\")]\n# upi_list = [ID for ID in IDs if ID.startswith(\"UPI\")]\n# query = ' '.join(upi_list)\n\n# params = {\n# 'from': 'UPARC',\n# 'to': 'ACC',\n# 'format': 'tab',\n# 'query': ''\n# }\n# \n# \n# params[\"query\"] = query\n# data = urllib.parse.urlencode(params)\n# data = data.encode('utf-8')\n# req = urllib.request.Request(url, data)\n# with urllib.request.urlopen(req) as f:\n# response = f.read()\n# #print(response.decode('utf-8'))\n\n# new_response = response[8:].decode()\n\n# p = re.compile(r'\\t([a-zA-Z0-9]+)')\n# uni_list_add = p.findall(new_response)\n\n# uni_list = uni_list + uni_list_add\n\n# uni_list = sorted(set(uni_list))\n\n# with open(outfile, 'w') as f: f.write('\\n'.join(uni_list) + '\\n')\n","sub_path":"Phylogenic_distance_library_generating/source_code/original_code/OutFile_Species_Uniref.py","file_name":"OutFile_Species_Uniref.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"18401110","text":"import turtle\nimport random\n\nturtle.speed('slowest')\n\ndef randomWalkb(length):\n steps = []\n x,y = 0,0\n walkx,walky = [x],[y]\n for i in range(length):\n\n new = random.randrange(0,150000)\n if new%4 == 0:\n x += 1\n elif new%4 == 2:\n y += 1\n elif new%4 == 1: \n x += -1\n else :\n y += -1\n walkx.append(x)\n walky.append(y)\n return [walkx,walky]\n\nwalk = randomWalkb(250000)\n\n\nfor x, y in zip(*walk):\n #multiply by 10, since 1 pixel differences are hard to see\n turtle.goto(x*10,y*10)\n\nturtle.exitonclick()","sub_path":"randomwalk.py","file_name":"randomwalk.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"166818634","text":"import numpy as np\nimport torch.nn.functional as F\nimport os\nimport torch\nfrom torch.autograd import grad\nfrom torch import nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport random\nimport torch.nn.init as init\nfrom numpy import linalg as LA\nimport math\n\n# layer for calculations - last hidden layer\nlayer_id = 8\nreparam_layers = [6,7]\n# dimensionality of the features\ndim = 84\n\n## get data\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\ntrainset = torchvision.datasets.CIFAR10(root='data/cifar10', train=True, download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=50000, shuffle=False, num_workers=1)\ntestset = torchvision.datasets.CIFAR10(root='data/cifar10', train=False, download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=10000, shuffle=False, num_workers=1)\ninputs, labels = iter(trainloader).next()\nx_train = inputs.cuda() # 1, 3, 32, 32,\ny_train = labels.cuda() # 1,\ninputs, labels = iter(testloader).next()\nx_test = inputs.cuda() # 1, 3, 32, 32,\ny_test = labels.cuda() # 1,\nprint(\"Data loaded\")\n\n\n# LeNet5\nclass LeNet5(nn.Module):\n def __init__(self):\n super(LeNet5, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def last_layer(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return x.view(-1, 84, 1)\n\n def classify(self, x):\n x = self.fc3(x)\n return x\n\n\n# directory with saved network state dictionaries after training\nfor f in os.listdir(\".\"):\n print(f, \"----------------------\")\n np.random.seed(None)\n # factor for reparametrization\n factor = np.random.randint(low=5, high=26) * 1.0\n print(\"Random reparametrization factor is\", factor)\n\n torch.manual_seed(7)\n torch.cuda.manual_seed_all(7)\n np.random.seed(7)\n random.seed(7)\n torch.backends.cudnn.deterministic = True\n\n model = LeNet5().cuda()\n model.load_state_dict(torch.load(f))\n model.eval()\n\n loss = nn.CrossEntropyLoss(reduction='none')\n \n ## test loss\n test_output = model(x_test)\n test_loss = loss(test_output, y_test)\n # since size of the test dataset is 5 times smaller we multiply loss by 5\n test_loss = np.sum(test_loss.data.cpu().numpy()) * 5\n print(\"Test loss\", test_loss)\n\n test_labels_np = y_test.data.cpu().numpy()\n test_output_np = test_output.data.cpu().numpy()\n test_acc = 0\n for i in range(len(test_labels_np)):\n if test_labels_np[i] == test_output_np[i].argmax():\n test_acc += 1\n print(\"Test accuracy is\", test_acc*1.0/len(test_labels_np))\n\n ## train loss\n train_output = model(x_train)\n train_loss = loss(train_output, y_train)\n train_loss_overall = np.sum(train_loss.data.cpu().numpy())\n print(\"Train loss\", train_loss_overall)\n\n train_labels_np = y_train.data.cpu().numpy()\n train_output_np = train_output.data.cpu().numpy()\n train_acc = 0\n for i in range(len(train_labels_np)):\n if train_labels_np[i] == train_output_np[i].argmax():\n train_acc += 1\n print(\"Train accuracy is\", train_acc*1.0/len(train_labels_np))\n\n ## calculate FisherRao norm\n # analytical formula for crossentropy loss from Appendix of the original paper\n sum_derivatives = 0\n m = nn.Softmax(dim=0)\n for inp in range(len(train_output)):\n sum_derivatives += \\\n (np.inner(m(train_output[inp]).data.cpu().numpy(), train_output[inp].data.cpu().numpy()) -\n train_output[inp].data.cpu().numpy()[train_labels_np[inp]]) ** 2\n fr_norm_origin = math.sqrt(((5 + 1) ** 2) * (1.0 / len(train_output)) * sum_derivatives)\n print(\"Fisher Rao norm is\", fr_norm_origin)\n\n loss = nn.CrossEntropyLoss()\n train_loss = loss(train_output, y_train)\n print(\"Train loss is\", train_loss)\n\n # hessian calculation for the layer of interest\n i = 0\n for p in model.parameters():\n if i == layer_id:\n last_layer = p\n i += 1\n last_layer_jacobian = grad(train_loss, last_layer, create_graph=True, retain_graph=True)\n hessian = []\n for n_grd in last_layer_jacobian[0]:\n for w_grd in n_grd:\n drv2 = grad(w_grd, last_layer, retain_graph=True)\n hessian.append(drv2[0].data.cpu().numpy().flatten())\n\n sum = 0.0\n for n in last_layer.data.cpu().numpy():\n for w in n:\n sum += w**2\n print(\"squared euclidian norm is calculated\", sum)\n\n max_eignv = LA.eigvalsh(hessian)[-1]\n print(\"largest eigenvalue is\", max_eignv)\n\n trace = np.trace(hessian)\n norm_trace = trace / (1.0*len(hessian))\n print(\"normalized trace is\", norm_trace)\n\n print(\"eigenvalue relative flatness is \", sum * max_eignv)\n print(\"tracial flatness is \", sum * norm_trace)\n\n # apply simplest reparametrization for ReLU network\n model = LeNet5().cuda()\n model.load_state_dict(torch.load(f))\n i = 0\n for l in model.parameters():\n if i in reparam_layers:\n l.data = l.data * 1.0/ factor\n elif i == layer_id:\n l.data = l.data * factor\n i += 1\n model.eval()\n\n loss = nn.CrossEntropyLoss(reduction='none')\n \n ## test loss\n test_output = model(x_test)\n test_loss = loss(test_output, y_test)\n # since size of the test dataset is 5 times smaller we multiply loss by 5\n test_loss = np.sum(test_loss.data.cpu().numpy()) * 5\n print(\"Test loss\", test_loss)\n\n test_labels_np = y_test.data.cpu().numpy()\n test_output_np = test_output.data.cpu().numpy()\n test_acc = 0\n for i in range(len(test_labels_np)):\n if test_labels_np[i] == test_output_np[i].argmax():\n test_acc += 1\n print(\"Test accuracy is\", test_acc*1.0/len(test_labels_np))\n\n ## train loss\n train_output = model(x_train)\n train_loss = loss(train_output, y_train)\n train_loss_overall = np.sum(train_loss.data.cpu().numpy())\n print(\"Train loss\", train_loss_overall)\n\n train_labels_np = y_train.data.cpu().numpy()\n train_output_np = train_output.data.cpu().numpy()\n train_acc = 0\n for i in range(len(train_labels_np)):\n if train_labels_np[i] == train_output_np[i].argmax():\n train_acc += 1\n print(\"Train accuracy is\", train_acc*1.0/len(train_labels_np))\n\n ## calculate FisherRao norm\n # analytical formula for crossentropy loss from the original paper\n train_labels_np = y_train.data.cpu().numpy()\n sum_derivatives = 0\n for inp in range(len(train_output)):\n sum_derivatives += \\\n (np.inner(m(train_output[inp]).data.cpu().numpy(), train_output[inp].data.cpu().numpy()) -\n train_output[inp].data.cpu().numpy()[train_labels_np[inp]]) ** 2\n fr_norm = math.sqrt(((5 + 1) ** 2) * (1.0 / len(train_output)) * sum_derivatives)\n print(\"Fisher Rao norm is\", fr_norm)\n\n loss = nn.CrossEntropyLoss()\n train_loss = loss(train_output, y_train)\n print(\"Train loss is\", train_loss)\n\n i = 0\n last_layer_id = 8\n for p in model.parameters():\n if i == last_layer_id:\n last_layer = p\n i += 1\n last_layer_jacobian = grad(train_loss, last_layer, create_graph=True, retain_graph=True)\n hessian = []\n for n_grd in last_layer_jacobian[0]:\n for w_grd in n_grd:\n drv2 = grad(w_grd, last_layer, retain_graph=True)\n hessian.append(drv2[0].data.cpu().numpy().flatten())\n\n sum = 0.0\n for n in last_layer.data.cpu().numpy():\n for w in n:\n sum += w**2\n print(\"squared euclidian norm is calculated\", sum)\n\n max_eignv = LA.eigvalsh(hessian)[-1]\n print(\"largest eigenvalue is\", max_eignv)\n\n trace = np.trace(hessian)\n norm_trace = trace / (1.0*len(hessian))\n print(\"normalized trace is\", norm_trace)\n\n print(\"eigenvalue relative flatness is \", sum * max_eignv)\n print(\"tracial flatness is \", sum * norm_trace)\n\n ### feature robustness calculation\n a = np.zeros((dim, dim, dim))\n np.fill_diagonal(a, 1)\n delta = 0.001\n robustness = []\n loss = nn.CrossEntropyLoss(reduction='none')\n train_loss_overall = loss(train_output, y_train)\n train_loss_overall = np.sum(train_loss_overall.data.cpu().numpy())\n\n ## train loss with noisy features\n for k in range(dim):\n activation = model.last_layer(x_train).data.cpu().numpy()\n added_noise = []\n for i in range(50000):\n added_noise.append(activation[i] + delta * np.dot(a[k], activation[i]))\n added_noise = np.array(added_noise).reshape(-1, dim)\n del activation\n train_output = model.classify(torch.cuda.FloatTensor(added_noise))\n train_loss_with_noise = loss(train_output, y_train)\n train_loss_overall_with_noise = np.sum(train_loss_with_noise.data.cpu().numpy())\n robustness.append((1.0 / len(train_loss_with_noise)) * (train_loss_overall_with_noise - train_loss_overall))\n print(\"Robustness\", robustness)\n","sub_path":"calculate_measures.py","file_name":"calculate_measures.py","file_ext":"py","file_size_in_byte":9541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"137149460","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import\nimport os\nimport numpy as np\nfrom .imdb import Imdb\nimport cv2\n\n\nclass Wider(Imdb):\n \"\"\"\n Implementation of Imdb for Pascal VOC datasets\n\n Parameters:\n ----------\n image_set : str\n set to be used, can be train, val, trainval, test\n root_path : str\n root path of wider dataset\n shuffle : boolean\n whether to initial shuffle the image list\n is_train : boolean\n if true, will load annotations\n \"\"\"\n def __init__(self, image_set, root_path, shuffle=False, is_train=False):\n super(Wider, self).__init__('WIDER_'+image_set)\n self.image_set = image_set\n self.root_path = root_path\n self.is_train = is_train\n self.classes = ['face']\n self.num_classes = len(self.classes)\n self.image_set_index = self._load_image_set_index(shuffle)\n self.num_images = len(self.image_set_index)\n if self.is_train:\n self.labels = self._load_image_labels()\n \n def _load_image_set_index(self, shuffle):\n \"\"\"\n find out which indexes correspond to given image set (train or val)\n\n Parameters:\n ----------\n shuffle : boolean\n whether to shuffle the image list\n Returns:\n ----------\n entire list of images specified in the setting\n \"\"\"\n image_set_index_file = os.path.join(self.root_path, self.name, 'images.list')\n assert os.path.exists(image_set_index_file), 'Path does not exist: {}'.format(image_set_index_file)\n with open(image_set_index_file) as f:\n image_set_index = [x.strip() for x in f.readlines()]\n if shuffle:\n np.random.shuffle(image_set_index)\n return image_set_index\n\n def image_path_from_index(self, index):\n \"\"\"\n given image index, find out full path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n Returns:\n ----------\n full path of this image\n \"\"\"\n assert self.image_set_index is not None, \"Dataset not initialized\"\n name = self.image_set_index[index]\n image_file = os.path.join(self.root_path, self.name, 'images', name)\n assert os.path.exists(image_file), 'Path does not exist: {}'.format(image_file)\n return image_file\n\n def label_from_index(self, index):\n \"\"\"\n given image index, return preprocessed ground-truth\n\n Parameters:\n ----------\n index: int\n index of a specific image\n Returns:\n ----------\n ground-truths of this image\n \"\"\"\n assert self.labels is not None, \"Labels not processed\"\n return self.labels[index]\n\n def _label_path_from_index(self, index):\n \"\"\"\n given image index, find out annotation path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n\n Returns:\n ----------\n full path of annotation file\n \"\"\"\n anno_path = 'wider_face_{}_info'.format(self.image_set)\n label_file = os.path.join(self.root_path, 'wider_face_split', anno_path, index.replace('.jpg', '.face_bbox'))\n assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file)\n return label_file\n\n def _load_image_labels(self):\n \"\"\"\n preprocess all ground-truths\n\n Returns:\n ----------\n labels packed in [num_images x max_num_objects x 5] tensor\n \"\"\"\n temp = []\n\n # load ground-truth from xml annotations\n for index in range(self.num_images):\n image_file = self.image_path_from_index(index)\n height, width = self._get_imsize(image_file)\n label_file = self._label_path_from_index(self.image_set_index[index])\n label = []\n with open(label_file) as f:\n for line in f.readlines():\n if not line.strip():\n continue\n items = [float(x) for x in line.strip().split()]\n assert len(items) == 4\n x,y,w,h=items\n label.append([0, x/width,y/height,(x+w)/width,(y+h)/height])\n temp.append(np.array(label))\n return temp\n\n def _get_imsize(self, im_name):\n \"\"\"\n get image size info\n Returns:\n ----------\n tuple of (height, width)\n \"\"\"\n img = cv2.imread(im_name)\n return (img.shape[0], img.shape[1])\n\nif __name__ == '__main__':\n root_path = r'D:\\res\\face_detect\\images\\WIDER'\n wider = Wider('val', root_path,True,True)\n print(wider.num_images)\n for idx in range(wider.num_classes):\n image_filename = wider.image_path_from_index(idx)\n label = wider.label_from_index(idx)\n print(image_filename)\n print(label)\n break","sub_path":"dataset/wider.py","file_name":"wider.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"510519820","text":"\"\"\"Ian Sahlberg\n12/20/2018\nPython 210 Assignment 3\"\"\"\n\n#Functions\n\ndef exchange_first_last(seq):\n \"\"\"This returns the first and last item of a sequence exchanged\"\"\"\n first = seq[-1:]\n mid = seq[1:-1]\n last = seq[:1]\n return print(first + mid + last)\n\ndef everyOther(val):\n \"\"\"This returns a sequence with every other value removed\"\"\"\n print(val[::2])\n\ndef foursOut(val):\n \"\"\"This returns a sequence with the first and last 4 values removed and every other value in between\"\"\"\n valRange = val[4:-4]\n return print(valRange[::2])\n\n\ndef reverseIt(val):\n \"\"\"This reutnr s a sequence in reverse order\"\"\"\n return print(val[::-1])\n\n#with the middle third, then last third, then the first third in the new order.\ndef thirds(val):\n \"\"\"This returns a sequence in the order of the middle third, then last third, then the first third.\"\"\"\n long = len(val)\n thirds = long//3\n first = val[:thirds]\n mid = val[thirds:(-1*thirds)]\n last = val[-1*thirds:]\n return print(mid+last+first)\n\n\n#Testing Area\n\n\nprint('Test first_last')\nexchange_first_last((1,2,3,4,5))\nexchange_first_last(('12345'))\nexchange_first_last([1,2,3,4,5])\nexchange_first_last([1,2,3])\n\n\nprint('Test every_other')\neveryOther('12345678')\neveryOther([1,2,3,4,5,6,7,8])\neveryOther((1,2,3,4,5,6,7,8))\n\nprint('Test foursOut')\nfoursOut([1,2,3,4,5,6,7,8,9,10,11,12])\nfoursOut('12345678910111213')\nfoursOut((1,2,3,4,5,6,7,8,9,10,11,12))\n\nprint('Test reverse_it')\nreverseIt('1,2,3,4,5')\nreverseIt([1,2,3,4,5])\nreverseIt((1,2,3,4,5))\n\nprint('Test thirds')\nthirds([1,2,3,4,5,6,7,8,9])\nthirds((1,2,3,4,5,6,7,8,9))\nthirds('abcdefghijkl')\nthirds('This is a string')\n","sub_path":"students/Sahlberg/Lesson3/Assignment3_StringSlicing.py","file_name":"Assignment3_StringSlicing.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"480883140","text":"# -*- coding: utf8 -*-\n\n# import socketserver\n# import threading\nfrom socket import *\nfrom select import *\n\nimport sys\nfrom time import ctime\nimport time\nimport datetime\nimport os\nimport json\nimport random\nfrom sys import exit\n\n'''\nsudo lsof -i tcp:27029\n'''\n\ndef timeFormat(endTime):\n return '{:02d}:{:02d}:{:02d}'.format(endTime // 3600, (endTime % 3600 // 60), endTime % 60)\n\nclass agent():\n def __init__(self, callNumber, callData):\n self.callNumber = callNumber\n self.callDataArray = callData\n self.callDataIndex = 0\n\n def getCallData(self):\n if self.callDataIndex == len(self.callDataArray):\n self.callDataIndex = 0\n idx = self.callDataIndex\n self.callDataIndex += 1\n return self.callDataArray[idx]\n\ndef getJsonStr(callNumber, entryNumber, speaker, sTime, eTime, sentence, status, uid):\n jsonStr = '{{\"callNumber\":\"{0}\", \"entryNumber\":\"{1}\", \"speaker\":\"{2}\", \"sTime\":\"{3}\", \"eTime\":\"{4}\", \"sentence\":\"{5}\", \"status\":\"{6}\", \"uid\":\"{7}\"}}'.format(callNumber, entryNumber, speaker, sTime, eTime, sentence, status, uid)\n return jsonStr\n\ndef setCallData(**options):\n callNumbers = options['callNumbers']\n entryNumbers = options['entryNumbers']\n testFileDir = options['testFileDir']\n startTime = options['startTime']\n\n callDataDict = {}\n for callNumber in callNumbers:\n callDataDict[callNumber] = []\n\n try:\n fileNames = os.listdir(testFileDir)\n for fileIdx, fileName in enumerate(fileNames):\n fullFileName = os.path.join(testFileDir, fileName)\n if os.path.isdir(fullFileName):\n setCallData(callNumbers, fullFileName)\n else:\n ext = os.path.splitext(fullFileName)[-1]\n # baseName = os.path.splitext(fileName)[0]\n if ext == '.dat':\n f = open(fullFileName, 'r', encoding='utf-8')\n if options['rf']:\n cn = random.choice(callNumbers)\n en = random.choice(entryNumbers)\n else:\n cn = callNumbers[fileIdx % 10]\n en = entryNumbers[fileIdx % 10]\n\n uid = str(startTime) + '_' + cn\n callDataDict[cn].append(getJsonStr(cn, en, '', '', '', '', 'start', uid))\n\n while True:\n line = f.readline()\n if not line: break\n arr = line.replace('\\n','').split('|')\n callDataDict[cn].append(getJsonStr(cn, en, arr[0], arr[1], arr[2], arr[3], 'pending', uid))\n\n callDataDict[cn].append(getJsonStr(cn, en, '', '', '', '', 'finish', uid))\n f.close()\n\n except PermissionError:\n pass\n\n return callDataDict\n\ndef runServer(**options):\n\n # addr = options['addr']\n # bufsize = options['bufsize']\n wc = options['wc']\n ac = options['ac']\n\n # 소켓 객체를 만들고..\n serverSocket = socket(AF_INET, SOCK_STREAM)\n\n # 서버 정보를 바인딩\n serverSocket.bind(options['addr'])\n\n # 요청을 기다림(listen)\n serverSocket.listen(10)\n connectionList = [serverSocket]\n print('==============================================')\n print('채팅 서버를 시작합니다. %s 포트로 접속을 기다립니다.' % str(options['addr'][1]))\n print('==============================================')\n\n # 무한 루프를 시작\n while connectionList:\n try:\n print('[INFO] 요청을 기다립니다...')\n\n # select 로 요청을 받고, 10초마다 블럭킹을 해제하도록 함\n read_socket, write_socket, error_socket = select(connectionList, [], [], 0.1)\n\n print('[INFO][{0}] 접속자수 : {1}'.format(ctime(), len(connectionList) - 1))\n # print('[INFO] now : ' + str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")))\n for sock in read_socket:\n # 새로운 접속\n if sock == serverSocket:\n clientSocket, addr_info = serverSocket.accept()\n connectionList.append(clientSocket)\n print('[INFO][{0}] 클라이언트({1})가 새롭게 연결 되었습니다.'.format(ctime(), addr_info[0]))\n\n # 접속한 사용자(클라이언트)로부터 새로운 데이터 받음\n else:\n data = sock.recv(options['bufsize'])\n if data:\n print('[INFO][{0}] 클라이언트로부터 데이터를 전달 받았습니다.'.format(ctime()))\n for clientSocket in connectionList:\n if clientSocket != serverSocket and clientSocket == sock:\n try:\n data = data.decode('utf-8')\n data = json.loads(data)\n # wc, ac 수정\n # ex) {wc:5, ac:10}\n # data 정보를 parsing 하여 형식이 일치하면 수정\n wc = data['wc']\n ac = data['ac']\n print('[INFO][{0}] 설정 정보 wc:{1}, ac:{2} 변경합니다.'.format(ctime(), wc, ac))\n except Exception as e:\n print(e)\n clientSocket.close()\n connectionList.remove(clientSocket)\n continue\n else:\n connectionList.remove(sock)\n sock.close()\n print('[INFO][{0}] 사용자와의 연결이 끊어졌습니다.'.format(ctime()))\n\n # 접속자에게 데이터 전달, 접속자가 없을경우 전달하지 않고 데이터 손실\n # agents 보다 ac 가 크면 agents 로 초기화\n ac = ac if len(options['agents']) > ac else len(options['agents'])\n slppeSecond = float(\"{0:.2f}\".format(wc / ac - 0.005)) # 내림\n print('[INFO][{0}] slppeSecond : {1}'.format(ctime(), slppeSecond))\n # print('[INFO][{0}] agents len : {1}'.format(ctime(), len(options['agents'])))\n for agent in options['agents'][:ac]:\n sendData = agent.getCallData()\n for clientSocket in connectionList:\n if clientSocket != serverSocket:\n try:\n clientSocket.send(sendData.encode('utf-8'))\n print('[INFO][{0}] send.'.format(ctime()))\n except Exception as e:\n print(e)\n connectionList.remove(clientSocket)\n clientSocket.close()\n print('[INFO][{0}] 사용자와의 연결이 끊어졌습니다.'.format(ctime()))\n time.sleep(slppeSecond)\n except KeyboardInterrupt:\n # 부드럽게 종료하기\n serverSocket.close()\n # sys.exit()\n\ndef main():\n # 호스트, 포트와 버퍼 사이즈를 지정\n host = ''\n port = 27029\n bufsize = 1024 * 5\n addr = (host, port)\n\n # 건당 대기 초\n wc = 3\n # 상담원수\n ac = 10\n # random 여부\n rf = False\n\n # test data 정보\n testFileDir = 'C:\\dev\\python\\data'\n callNumberFormat='1544-{0}'\n entryNumberFormat='010-1234-{0}'\n numberOfAgents = 10\n callNumbers = []\n entryNumbers = []\n agents = []\n\n for i in range(1, numberOfAgents+1):\n callNumbers.append(callNumberFormat.format(\"%04d\" % i))\n entryNumbers.append(entryNumberFormat.format(\"%04d\" % i))\n\n startTime = time.time()\n startTimeApplyFormat = str(datetime.datetime.fromtimestamp(startTime).strftime('%Y%m%d%H%M%S%f'))\n print('+++ call data 생성 시작')\n callDataDict = setCallData(callNumbers=callNumbers, entryNumbers=entryNumbers, testFileDir=testFileDir, rf=rf, startTime=startTimeApplyFormat)\n for k, v in callDataDict.items():\n if v :\n agents.append(agent(k, v))\n\n print('+++ call data 생성 종료')\n print('+++ call data 생성 시간 : {0}'.format(timeFormat(int(time.time() - startTime))))\n\n print('+++ agents count : ' + str(len(agents)))\n\n print('+++ STT 서버를 시작')\n print('+++ STT 서버를 끝내려면 Ctrl-C를 누르세요.')\n runServer(addr=addr, bufsize=bufsize, wc=wc, ac=ac, agents=agents)\n\nmain()\n","sub_path":"socket/TcpCallServerForWindow.py","file_name":"TcpCallServerForWindow.py","file_ext":"py","file_size_in_byte":8669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"63532233","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport abc\nfrom typing import Awaitable, Callable, Dict, Optional, Sequence, Union\n\nfrom google.cloud.bigtable_v2 import gapic_version as package_version\n\nimport google.auth # type: ignore\nimport google.api_core\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.cloud.bigtable_v2.types import bigtable\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=package_version.__version__\n)\n\n\nclass BigtableTransport(abc.ABC):\n \"\"\"Abstract transport class for Bigtable.\"\"\"\n\n AUTH_SCOPES = (\n \"https://www.googleapis.com/auth/bigtable.data\",\n \"https://www.googleapis.com/auth/bigtable.data.readonly\",\n \"https://www.googleapis.com/auth/cloud-bigtable.data\",\n \"https://www.googleapis.com/auth/cloud-bigtable.data.readonly\",\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"https://www.googleapis.com/auth/cloud-platform.read-only\",\n )\n\n DEFAULT_HOST: str = \"bigtable.googleapis.com\"\n\n def __init__(\n self,\n *,\n host: str = DEFAULT_HOST,\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n api_audience: Optional[str] = None,\n **kwargs,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A list of scopes.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n \"\"\"\n\n scopes_kwargs = {\"scopes\": scopes, \"default_scopes\": self.AUTH_SCOPES}\n\n # Save the scopes.\n self._scopes = scopes\n\n # If no credentials are provided, then determine the appropriate\n # defaults.\n if credentials and credentials_file:\n raise core_exceptions.DuplicateCredentialArgs(\n \"'credentials_file' and 'credentials' are mutually exclusive\"\n )\n\n if credentials_file is not None:\n credentials, _ = google.auth.load_credentials_from_file(\n credentials_file, **scopes_kwargs, quota_project_id=quota_project_id\n )\n elif credentials is None:\n credentials, _ = google.auth.default(\n **scopes_kwargs, quota_project_id=quota_project_id\n )\n # Don't apply audience if the credentials file passed from user.\n if hasattr(credentials, \"with_gdch_audience\"):\n credentials = credentials.with_gdch_audience(\n api_audience if api_audience else host\n )\n\n # If the credentials are service account credentials, then always try to use self signed JWT.\n if (\n always_use_jwt_access\n and isinstance(credentials, service_account.Credentials)\n and hasattr(service_account.Credentials, \"with_always_use_jwt_access\")\n ):\n credentials = credentials.with_always_use_jwt_access(True)\n\n # Save the credentials.\n self._credentials = credentials\n\n # Save the hostname. Default to port 443 (HTTPS) if none is specified.\n if \":\" not in host:\n host += \":443\"\n self._host = host\n\n def _prep_wrapped_messages(self, client_info):\n # Precompute the wrapped methods.\n self._wrapped_methods = {\n self.read_rows: gapic_v1.method.wrap_method(\n self.read_rows,\n default_timeout=43200.0,\n client_info=client_info,\n ),\n self.sample_row_keys: gapic_v1.method.wrap_method(\n self.sample_row_keys,\n default_timeout=60.0,\n client_info=client_info,\n ),\n self.mutate_row: gapic_v1.method.wrap_method(\n self.mutate_row,\n default_retry=retries.Retry(\n initial=0.01,\n maximum=60.0,\n multiplier=2,\n predicate=retries.if_exception_type(\n core_exceptions.DeadlineExceeded,\n core_exceptions.ServiceUnavailable,\n ),\n deadline=60.0,\n ),\n default_timeout=60.0,\n client_info=client_info,\n ),\n self.mutate_rows: gapic_v1.method.wrap_method(\n self.mutate_rows,\n default_timeout=600.0,\n client_info=client_info,\n ),\n self.check_and_mutate_row: gapic_v1.method.wrap_method(\n self.check_and_mutate_row,\n default_timeout=20.0,\n client_info=client_info,\n ),\n self.ping_and_warm: gapic_v1.method.wrap_method(\n self.ping_and_warm,\n default_timeout=None,\n client_info=client_info,\n ),\n self.read_modify_write_row: gapic_v1.method.wrap_method(\n self.read_modify_write_row,\n default_timeout=20.0,\n client_info=client_info,\n ),\n self.generate_initial_change_stream_partitions: gapic_v1.method.wrap_method(\n self.generate_initial_change_stream_partitions,\n default_timeout=60.0,\n client_info=client_info,\n ),\n self.read_change_stream: gapic_v1.method.wrap_method(\n self.read_change_stream,\n default_timeout=43200.0,\n client_info=client_info,\n ),\n }\n\n def close(self):\n \"\"\"Closes resources associated with the transport.\n\n .. warning::\n Only call this method if the transport is NOT shared\n with other clients - this may cause errors in other clients!\n \"\"\"\n raise NotImplementedError()\n\n @property\n def read_rows(\n self,\n ) -> Callable[\n [bigtable.ReadRowsRequest],\n Union[bigtable.ReadRowsResponse, Awaitable[bigtable.ReadRowsResponse]],\n ]:\n raise NotImplementedError()\n\n @property\n def sample_row_keys(\n self,\n ) -> Callable[\n [bigtable.SampleRowKeysRequest],\n Union[\n bigtable.SampleRowKeysResponse, Awaitable[bigtable.SampleRowKeysResponse]\n ],\n ]:\n raise NotImplementedError()\n\n @property\n def mutate_row(\n self,\n ) -> Callable[\n [bigtable.MutateRowRequest],\n Union[bigtable.MutateRowResponse, Awaitable[bigtable.MutateRowResponse]],\n ]:\n raise NotImplementedError()\n\n @property\n def mutate_rows(\n self,\n ) -> Callable[\n [bigtable.MutateRowsRequest],\n Union[bigtable.MutateRowsResponse, Awaitable[bigtable.MutateRowsResponse]],\n ]:\n raise NotImplementedError()\n\n @property\n def check_and_mutate_row(\n self,\n ) -> Callable[\n [bigtable.CheckAndMutateRowRequest],\n Union[\n bigtable.CheckAndMutateRowResponse,\n Awaitable[bigtable.CheckAndMutateRowResponse],\n ],\n ]:\n raise NotImplementedError()\n\n @property\n def ping_and_warm(\n self,\n ) -> Callable[\n [bigtable.PingAndWarmRequest],\n Union[bigtable.PingAndWarmResponse, Awaitable[bigtable.PingAndWarmResponse]],\n ]:\n raise NotImplementedError()\n\n @property\n def read_modify_write_row(\n self,\n ) -> Callable[\n [bigtable.ReadModifyWriteRowRequest],\n Union[\n bigtable.ReadModifyWriteRowResponse,\n Awaitable[bigtable.ReadModifyWriteRowResponse],\n ],\n ]:\n raise NotImplementedError()\n\n @property\n def generate_initial_change_stream_partitions(\n self,\n ) -> Callable[\n [bigtable.GenerateInitialChangeStreamPartitionsRequest],\n Union[\n bigtable.GenerateInitialChangeStreamPartitionsResponse,\n Awaitable[bigtable.GenerateInitialChangeStreamPartitionsResponse],\n ],\n ]:\n raise NotImplementedError()\n\n @property\n def read_change_stream(\n self,\n ) -> Callable[\n [bigtable.ReadChangeStreamRequest],\n Union[\n bigtable.ReadChangeStreamResponse,\n Awaitable[bigtable.ReadChangeStreamResponse],\n ],\n ]:\n raise NotImplementedError()\n\n @property\n def kind(self) -> str:\n raise NotImplementedError()\n\n\n__all__ = (\"BigtableTransport\",)\n","sub_path":"google/cloud/bigtable_v2/services/bigtable/transports/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"279472909","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport matplotlib.cm as cm\n\n\ndef plot_episode(action_data):\n num_options = action_data.shape[1] - 2\n step_no, x, z = [action_data[:, i] for i in range(3)]\n option_idx = action_data[:, -num_options:].argmax(axis=1) \n colors = cm.rainbow(np.linspace(0, 1, num_options))\n plt.figure()\n for i in range(num_options):\n idx = option_idx == i\n plt.scatter(x[idx], z[idx], color=colors[i]) \n plt.savefig('action_plot.png')\naction_data_file = sys.argv[1]\nlines = open(action_data_file).readlines()\n\n\nfor line in lines:\n # Organized as train_timestep s1 s2 s3\n # s1 = step_no,x,z,o1,o2,o3\n line_data = line.rstrip().split('\\t')\n train_timestep = line_data[0]\n action_data = [x.split(',') for x in line_data[1:-1]]\n \n action_data = np.asarray(action_data)\n plot_episode(action_data)\n break\n\n \n","sub_path":"RL/src/plot_actions.py","file_name":"plot_actions.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"600401105","text":"import logging\nimport os\nimport sys\n\nfrom nevermined_sdk_py import Config\n\n\ndef get_variable_value(variable):\n if os.getenv(variable) is None:\n logging.error(f'you should provide a {variable}')\n sys.exit(1)\n else:\n return os.getenv(variable)\n\n\nclass ExampleConfig:\n _local_metadata_url = \"http://localhost:5000\"\n _local_gateway_url = \"http://localhost:8030\"\n _duero_metadata_url = \"https://metadata.compute.duero.dev-ocean.com\"\n _duero_gateway_url = \"https://gateway.compute.duero.dev-ocean.com\"\n # _duero_metadata_url = \"http://localhost:5000\"\n # _duero_gateway_url = \"http://localhost:8030\"\n\n _pacific_metadata_url = \"https://metadata.pacific.dev-ocean.com\"\n _pacific_gateway_url = \"https://gateway.pacific.dev-ocean.com\"\n\n # _nile_metadata_url = \"http://172.15.0.15:5000\"\n\n # _nile_metadata_url = \"https://nginx-metadata.dev-ocean.com\"\n # _nile_gateway_url = \"https://nginx-gateway.dev-ocean.com\"\n # _nile_metadata_url = \"https://nginx-metadata.dev-ocean.com\"\n _nile_metadata_url = \"https://metadata.marketplace.dev-ocean.com\"\n # _nile_metadata_url = \"http://172.15.0.15:5000\"\n _nile_gateway_url = \"https://gateway.marketplace.dev-ocean.com\"\n # _nile_gateway_url = \"http://localhost:8030\"\n\n _duero_secret_store_url = \"https://secret-store.duero.dev-ocean.com\"\n _nile_secret_store_url = \"https://secret-store.dev-ocean.com\"\n _pacific_secret_store_url = \"https://secret-store.pacific.oceanprotocol.com\"\n # _nile_secret_store_url = \"https://secret-store.marketplace.dev-ocean.com\"\n _kovan_keeper_url = \"http://localhost:8545\"\n _remote_keeper_url = \"https://%s.dev-ocean.com\"\n _parity_url = \"http://localhost:8545\"\n _net_to_services_url = {\n 'duero': {'metadata': _duero_metadata_url, 'gateway': _duero_gateway_url},\n 'nile': {'metadata': _nile_metadata_url, 'gateway': _nile_gateway_url},\n 'kovan': {'metadata': _local_metadata_url, 'gateway': _local_gateway_url},\n 'pacific': {'metadata': _pacific_metadata_url, 'gateway': _pacific_gateway_url},\n }\n _net_name_map = {\n 'duero': 'duero',\n 'duero_local': 'duero',\n 'nile': 'nile',\n 'nile_local': 'nile',\n 'kovan': 'kovan',\n 'kovan_local': 'kovan',\n 'pacific': 'pacific',\n 'pacific_local': 'pacific'\n }\n _net_to_env_name = {\n 'nile': 'TEST_NILE',\n 'nile_local': 'TEST_LOCAL_NILE',\n 'duero': 'TEST_DUERO',\n 'duero_local': 'TEST_LOCAL_DUERO',\n 'spree': 'TEST_LOCAL_SPREE',\n 'kovan': 'TEST_KOVAN',\n 'kovan_local': 'TEST_LOCAL_KOVAN',\n 'pacific': 'TEST_PACIFIC',\n 'pacific_local': 'TEST_LOCAL_PACIFIC'\n\n }\n\n @staticmethod\n def get_config_net():\n return os.environ.get('TEST_NET', 'spree')\n\n @staticmethod\n def get_env_name():\n net = ExampleConfig.get_config_net()\n return ExampleConfig._net_to_env_name.get(net)\n\n @staticmethod\n def get_base_config():\n config = {\n \"keeper-contracts\": {\n \"keeper.url\": \"http://172.17.0.1:8545\",\n \"keeper.path\": \"artifacts\",\n \"secret_store.url\": \"http://172.17.0.1:12001\",\n \"parity.url\": \"http://172.17.0.1:8545\",\n },\n \"resources\": {\n \"metadata.url\": \"http://172.17.0.1:5000\",\n # \"metadata.url\": \"http://localhost:5000\",\n # \"gateway.url\": \"http://172.15.0.17:8030\",\n \"gateway.url\": \"http://172.17.0.1:8030\",\n \"storage.path\": \"sdk.db\",\n \"downloads.path\": \"access-downloads\"\n }\n }\n return config\n\n @staticmethod\n def _get_config(local_node=True, net_key=''):\n config = ExampleConfig.get_base_config()\n net_name = ExampleConfig._net_name_map.get(net_key)\n if net_name == 'kovan':\n config['keeper-contracts']['keeper.url'] = ExampleConfig._kovan_keeper_url\n elif net_name == 'pacific':\n config['keeper-contracts']['keeper.url'] = 'https://pacific.oceanprotocol.com'\n config['keeper-contracts']['parity.url'] = 'https://pacific.oceanprotocol.com'\n elif not local_node:\n config['keeper-contracts']['keeper.url'] = ExampleConfig._remote_keeper_url % net_name\n config['keeper-contracts']['parity.url'] = ExampleConfig._remote_keeper_url % net_name\n if net_name:\n config['keeper-contracts']['secret_store.url'] = \\\n ExampleConfig._duero_secret_store_url if net_name == 'duero' \\\n else ExampleConfig._nile_secret_store_url\n\n service_url = ExampleConfig._net_to_services_url[net_name]\n config['resources']['metadata.url'] = service_url['metadata']\n config['resources']['gateway.url'] = service_url['gateway']\n\n # parity_url maybe different than the keeper_url\n # config['keeper-contracts']['parity.url'] = ExampleConfig._parity_url\n return config\n\n @staticmethod\n def get_config_dict():\n test_net = ExampleConfig.get_config_net()\n local_node = not test_net or test_net in (\n 'nile_local', 'duero_local', 'spree', 'kovan_local')\n config_dict = ExampleConfig._get_config(local_node, test_net)\n return config_dict\n\n @staticmethod\n def get_config():\n logging.debug(\"Configuration loaded for environment '{}'\"\n .format(ExampleConfig.get_config_net()))\n return Config(options_dict=ExampleConfig.get_config_dict())\n","sub_path":"examples/example_config.py","file_name":"example_config.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"503142100","text":"import math\nfrom functools import partial\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nfrom .deleteThread import DeleteThread\nfrom .diarizerThread import DiarizerThread\nfrom .Import_Dialog import Import_Dialog\nfrom .Player import Player\nfrom .repository.segments import Segments\nfrom .repository.team import Team\nfrom .repository.upload import Upload\nfrom .status import Status\nfrom .views.label import Label\nfrom .views.Ui_MainWindow import Ui_MainWindow\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n self.show()\n self.offset = 0\n self.processing = 0\n self.refresh()\n self.page_box.currentTextChanged.connect(\n partial(self.refresh, offset=True))\n self.import_btn.clicked.connect(self.show_import)\n self.search_edit.textChanged.connect(self.search)\n self.refresh_btn.clicked.connect(self.refresh)\n self.next_btn.clicked.connect(self.inc_offset)\n self.previous.clicked.connect(self.dec_offset)\n self.page_combo.currentTextChanged.connect(self.goto_page)\n\n def goto_page(self):\n page_no = self.page_combo.currentIndex()\n size = self.get_size()\n self.offset = page_no * size\n self.refresh(combo=False)\n\n def inc_offset(self):\n index = self.page_combo.currentIndex()\n count = self.page_combo.count()\n if index < (count - 1):\n self.page_combo.setCurrentIndex(index+1)\n\n def dec_offset(self):\n index = self.page_combo.currentIndex()\n if index > 0:\n self.page_combo.setCurrentIndex(index-1)\n\n def show_import(self):\n self.dialog = QtWidgets.QDialog()\n self.window = Import_Dialog()\n self.window.setupUi(self.dialog)\n self.dialog.show()\n\n def search(self):\n self.recordings_table.setRowCount(0)\n query = self.search_edit.text()\n size = self.get_size()\n if query:\n uploads = Upload.get_by(query, size)\n self.fill_table(uploads)\n else:\n self.refresh()\n\n def get_size(self):\n try:\n size = int(self.page_box.currentText())\n except ValueError:\n size = 5\n return size\n\n def refresh(self, combo=True, offset=False):\n if offset:\n self.offset = 0\n size = self.get_size()\n uploads = Upload.get_all(self.offset, size)\n self.search_edit.setText(\"\")\n if combo:\n self.page_combo.clear()\n count = math.floor(float(Upload.get_count()) / size)\n self.page_combo.addItems([str(item + 1)\n for item in range(count + 1)])\n self.goto_page()\n self.recordings_table.setRowCount(0)\n self.fill_table(uploads)\n\n def get_label(self, status):\n if status == \"Processed\":\n processed_btn = QtWidgets.QPushButton()\n processed_btn.setObjectName(\"processed\")\n\n processed_btn.setIcon(QtGui.QIcon(\":icons/play-button.svg\"))\n processed_btn.setIconSize(QtCore.QSize(25, 25))\n processed_btn.setToolTip(\"Processed\")\n return processed_btn\n\n if status == \"Process\":\n start_lbl = Label()\n start_lbl.setObjectName(\"processing\")\n start_lbl.setStyleSheet(\n \"\"\"color:black;height:30px;border-radius:5px;background-color:lightgray;width:80px;padding:5px;\"\"\")\n # start_lbl.setText('\\u25B6')\n start_lbl.setText(\"Process\")\n start_lbl.setToolTip(\"Process\")\n return start_lbl\n\n def fill_table(self, uploads):\n self.recordings_table.setSortingEnabled(False)\n for upload in uploads:\n row = self.recordings_table.rowCount()\n self.recordings_table.insertRow(row)\n item = QtWidgets.QTableWidgetItem(\n Team.get_name(upload.team_id))\n item.setTextAlignment(QtCore.Qt.AlignHCenter |\n QtCore.Qt.AlignVCenter)\n self.recordings_table.setItem(row, 0, item)\n\n audio_name = QtWidgets.QTableWidgetItem(\n upload.name)\n audio_name.setTextAlignment(QtCore.Qt.AlignHCenter |\n QtCore.Qt.AlignVCenter)\n\n self.recordings_table.setItem(row, 1, audio_name)\n date = QtWidgets.QTableWidgetItem(\n upload.upload_time.strftime(\"%Y-%m-%d\"))\n date.setTextAlignment(QtCore.Qt.AlignHCenter |\n QtCore.Qt.AlignVCenter)\n self.recordings_table.setItem(row, 2, date)\n\n duration = QtWidgets.QTableWidgetItem(\n self.milli_to_Minutes(upload.duration))\n duration.setTextAlignment(QtCore.Qt.AlignHCenter |\n QtCore.Qt.AlignVCenter)\n self.recordings_table.setItem(row, 3, duration)\n\n if len(str(upload.description)) > 15:\n description = QtWidgets.QTableWidgetItem(\n \"{0} ...\".format(str(upload.description)[:15]))\n else:\n description = QtWidgets.QTableWidgetItem(\n \"{0}\".format(str(upload.description)))\n description.setTextAlignment(QtCore.Qt.AlignHCenter |\n QtCore.Qt.AlignVCenter)\n description.setToolTip(str(upload.description))\n self.recordings_table.setItem(\n row, 4, description)\n\n self.pWidget = QtWidgets.QWidget()\n btn_status = self.get_label(Status(int(upload.status)).name)\n\n if btn_status.objectName() == \"processed\":\n btn_status.clicked.connect(\n partial(self.open_audio, upload.upload_id, upload.status))\n else:\n btn_status.clicked.connect(\n partial(self.process, upload.upload_id, btn_status))\n self.playout = QtWidgets.QHBoxLayout(self.pWidget)\n self.playout.addWidget(\n btn_status, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)\n\n self.recordings_table.setCellWidget(row, 5, self.pWidget)\n\n self.edit_Widget = QtWidgets.QWidget()\n edit_btn = QtWidgets.QPushButton()\n edit_btn.setObjectName(\"delete_btn\")\n\n edit_btn.setIcon(QtGui.QIcon(\":/icons/pencil-edit.svg\"))\n edit_btn.setIconSize(QtCore.QSize(25, 25))\n edit_btn.clicked.connect(partial(self.edit_view, upload))\n\n self.playout = QtWidgets.QHBoxLayout(self.edit_Widget)\n self.playout.addWidget(\n edit_btn, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)\n\n self.recordings_table.setCellWidget(row, 6, self.edit_Widget)\n\n self.pWidget = QtWidgets.QWidget()\n delete_btn = QtWidgets.QPushButton()\n delete_btn.setObjectName(\"delete_btn\")\n\n delete_btn.setIcon(QtGui.QIcon(\":/icons/rubbish-bin.svg\"))\n delete_btn.setIconSize(QtCore.QSize(25, 25))\n\n self.playout = QtWidgets.QHBoxLayout(self.pWidget)\n self.playout.addWidget(\n delete_btn, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)\n\n self.recordings_table.setCellWidget(row, 7, self.pWidget)\n\n if self.processing == upload.upload_id:\n\n size = QtCore.QSize(40, 40)\n self.movie = QtGui.QMovie(\":/icons/processing.gif\")\n btn_status.setMovie(self.movie)\n self.movie.start()\n self.movie.setScaledSize(size)\n # self.recordings_table.verticalHeader().setSectionResizeMode(\n # row, QtWidgets.QHeaderView.ResizeToContents)\n delete_btn.clicked.connect(\n partial(self.confirm_delete, upload.upload_id))\n\n # self.recordings_table.resizeColumnsToContents()\n self.recordings_table.resizeRowsToContents()\n self.recordings_table.setSortingEnabled(True)\n self.pagination_lbl.setText(\n \"Showing {0} of {1} entries\".format(self.recordings_table.rowCount(), Upload.get_count()))\n\n def edit_view(self, upload):\n self.dialog = QtWidgets.QDialog()\n self.window = Import_Dialog()\n self.window.setupUi(self.dialog, upload)\n self.dialog.show()\n\n def open_audio(self, id, status):\n if status == \"2\":\n self.player = Player(id)\n self.player.show()\n else:\n self.msg_box = QtWidgets.QMessageBox()\n self.msg_box.setWindowIcon(QtGui.QIcon(\":/icons/logo-square.png\"))\n self.msg_box.setText(\"Not yet Diarized\")\n self.msg_box.setWindowTitle(\"No View Available\")\n self.msg_box.exec_()\n\n def process(self, id, btn):\n if self.processing == 0:\n # if btn.text() == '\\u25B6':\n if btn.text() == 'Process':\n # trashGif = str(Path(__file__).parent) + \\\n # os.sep + \"images\" + os.sep + \"processing.gif\"\n size = QtCore.QSize(35, 35)\n self.movie = QtGui.QMovie(\":/icons/processing.gif\")\n btn.setMovie(self.movie)\n btn.setStyleSheet(\"\"\"background-color:none\"\"\")\n self.movie.start()\n self.movie.setScaledSize(size)\n self.processing = id\n queue = Upload.get(id)\n self.diarize_thread = DiarizerThread(\n queue.upload_id, queue.speaker)\n self.diarize_thread.start()\n self.diarize_thread.finished.connect(\n partial(self.update_segments, self.diarize_thread.segs, btn, queue.upload_id))\n btn.setToolTip(\"Processing\")\n elif btn.objectName() != \"processed\":\n self.invalid_status = QtWidgets.QMessageBox()\n self.invalid_status.setText(\"Invalid Status for Diarzation\")\n self.invalid_status.setStandardButtons(\n QtWidgets.QMessageBox().Ok)\n self.invalid_status.setWindowTitle(\"Invalid Status\")\n self.invalid_status.exec_()\n\n else:\n self.in_queue = QtWidgets.QMessageBox()\n self.in_queue.setWindowIcon(QtGui.QIcon(\":/icons/logo-square.png\"))\n self.in_queue.setText(\n \"Cannot process more than one recording at a time\")\n self.in_queue.setStandardButtons(QtWidgets.QMessageBox.Ok)\n self.in_queue.setWindowTitle(\"Warning\")\n self.in_queue.exec_()\n\n def update_segments(self, segs, btn, id):\n if segs != []:\n Segments.add_all(segs, id)\n Upload.update_status_by_id(id, value=2)\n else:\n self.failure_msg_box = QtWidgets.QMessageBox()\n self.failure_msg_box.setWindowIcon(\n QtGui.QIcon(\":/icons/logo-square.png\"))\n self.failure_msg_box.setWindowTitle(\"Failed\")\n self.failure_msg_box.setText(\n \"Unable to Process.Try Freeing Resources on your machine and Try Later\")\n self.failure_msg_box.setStandardButtons(QtWidgets.QMessageBox().Ok)\n self.failure_msg_box.exec_()\n btn.setText(Status.Process.name)\n self.processing = 0\n self.refresh()\n\n def confirm_delete(self, upload_id):\n self.delete_msg_box = QtWidgets.QMessageBox()\n self.delete_msg_box.setWindowIcon(\n QtGui.QIcon(\":/icons/logo-square.png\"))\n self.delete_msg_box.setText(\n \" Delete \" + str(Upload.get_by_id(upload_id).name) + \" ?\")\n self.delete_msg_box.setWindowTitle(\"Confirm Delete\")\n self.delete_msg_box.setStandardButtons(\n QtWidgets.QMessageBox().Yes | QtWidgets.QMessageBox().Cancel)\n self.delete_msg_box.button(QtWidgets.QMessageBox.Yes).setStyleSheet(\n \"\"\"background:rgb(255,102,102);height:20px;padding:5px;\"\"\")\n self.delete_msg_box.button(QtWidgets.QMessageBox.Cancel).setStyleSheet(\n \"\"\"background:SILVER;height:20px;padding:5px;\"\"\")\n self.returnvalue = self.delete_msg_box.exec_()\n if self.returnvalue == QtWidgets.QMessageBox().Yes:\n self.delete(upload_id)\n\n def delete(self, id):\n if self.processing != id:\n self.delete_thread = DeleteThread(id)\n self.delete_thread.start()\n self.delete_thread.finished.connect(\n partial(self.remove_from_db, id))\n else:\n self.in_proc_warning = QtWidgets.QMessageBox()\n self.in_proc_warning.setWindowIcon(\n QtGui.QIcon(\":/icons/logo-square.png\"))\n self.in_proc_warning.setText(\"Cannot Delete While Diarizing\")\n self.in_proc_warning.setWindowTitle(\"Cannot Delete\")\n self.in_proc_warning.setStandardButtons(QtWidgets.QMessageBox().Ok)\n self.in_proc_warning.exec_()\n\n def remove_from_db(self, id):\n Upload.delete_by_id(id)\n Segments.remove(id)\n self.refresh()\n\n @staticmethod\n def milli_to_Minutes(duration):\n seconds = (duration) % 60\n minutes = (duration/60) % 60\n hours = (duration/3600) % 24\n dur = QtCore.QTime(hours, minutes, seconds)\n return dur.toString()\n","sub_path":"MeetingBites/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":13392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"607894964","text":"import socket\nimport time\nimport paramiko\nfrom utils.utils import AuthFailure\n\nclass SSH:\n\n def __init__(self, hostname, port, timeout):\n self.hostname = hostname\n self.port = port\n self.timeout = timeout\n\n self.conn = None\n\n def url(self):\n return 'ssh://%s:%d' % (self.hostname, self.port)\n\n def get_version(self):\n try:\n sock = socket.socket()\n sock.settimeout(self.timeout)\n sock.connect((self.hostname, self.port))\n\n banner_raw = sock.recv(1024)\n\n if banner_raw[:3] == b\"SSH\":\n try:\n return banner_raw.decode().rstrip()\n except UnicodeDecodeError:\n return None\n else:\n return None\n except ConnectionRefusedError:\n return None\n except OSError:\n return None\n\n def auth(self, username, password):\n self.conn = paramiko.Transport((self.hostname, self.port))\n self.conn.connect(username=username, password=password)\n\n return True\n\n def execute(self, command):\n chan = self.conn.open_channel(\"session\")\n chan.settimeout(self.timeout)\n\n result = ''\n\n chan.exec_command(command)\n stdin = chan.makefile_stdin(\"wb\", -1)\n stdout = chan.makefile(\"r\", -1)\n stderr = chan.makefile_stderr(\"r\", -1)\n\n result = stdout.read()\n result += stderr.read()\n\n chan.close()\n\n return result.decode()\n\n def disconnect(self):\n if self.conn:\n self.conn.close()\n self.conn = None\n","sub_path":"lib/sshscan/ssh.py","file_name":"ssh.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"10939238","text":"import os\nfrom colour_remap import colour_remap\nfilecontents = open(\"gtk.css.original\").read()\n\ncolours = filecontents.split(\"#\")\ncolours.pop(0)\n\ndiscovered_colours = set()\nfor i in colours:\n i = \"#%s;\" % i.split(\";\")[0]\n if len(i) == 8:\n discovered_colours.add(i)\n \nfor k, v in colour_remap.items():\n# print(\"--- replacing %s with %s \" % (k, v))\n filecontents = filecontents.replace(k, v)\n#filecontents = (filecontents.replace(\"border-radius: 2px\", \"border-radius: 8px\")\n# .replace(\"border-radius: 1px\", \"border-radius: 8px\"))\n \n\nif os.path.exists(\"gtk.css\"):\n os.remove(\"gtk.css\")\n \nwith open(\"gtk.css\", \"w\") as fhandle:\n fhandle.write(filecontents)\nprint(\"Written to file\")\n\nmissing_remaps = list(discovered_colours - set(colour_remap.keys()))\nmissing_remaps.sort()\n#print(\"----- Missing remaps ----- \")\nfor i in missing_remaps:\n print(\" \\\"%s\\\": \\\"\\\",\" % i)\n \n","sub_path":"gtk-3.0/strip_colours.py","file_name":"strip_colours.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"371799542","text":"import numpy as np\r\nfrom numpy import genfromtxt\r\nimport datetime\r\nfrom scipy.optimize import minimize\r\nfrom scipy.special import gamma\r\nfrom numpy import genfromtxt\r\nimport os\r\nimport math\r\nfrom scipy.optimize import Bounds\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n \r\nconf_matrix = genfromtxt('C:\\\\Users\\\\jacgwatkins\\\\Data\\\\z_code\\\\minimization_code\\\\conf_matrix.txt')\t\t### load inverse confusion matrix from saved file, the correct one, transposed such that sum(col) = 1\r\n\t\r\ncov_matrix = genfromtxt('C:\\\\Users\\\\jacgwatkins\\\\Data\\\\z_code\\\\minimization_code\\\\cov_matrix.txt')\t\t### load covariance matrix from saved file (obtained from classification algorithm performance)\r\n\r\ninv_cov_matrix = np.linalg.inv(cov_matrix)\r\n\r\ninv_conf_matrix = np.linalg.inv(conf_matrix) \r\n\r\navg_array = inv_conf_matrix.flatten() ### flattened confusion matrix of averages, to be later subtracted from r_array\r\n\r\n\r\n## matrices used for defining boundaries in minimization for defining boundaries:\r\ndiag_cov_matrix = np.zeros(36)\r\n\r\nfor i in range(36):\r\n diag_cov_matrix[i] = cov_matrix[i][i]\r\n \r\ndiag_cov_matrix = np.reshape(diag_cov_matrix, (6,6))\r\ndiag_cov_matrix = diag_cov_matrix.transpose()\r\ndiag_cov_matrix = diag_cov_matrix.flatten()\r\n\r\n\r\nflat_conf_matrix = conf_matrix.transpose()\r\nflat_conf_matrix = flat_conf_matrix.flatten()\r\n\r\n\r\nglobal bnd\r\n\r\nbnd = []\r\n \r\nfor i in range(36):\r\n \r\n bnd.append((max(flat_conf_matrix[i] - 3 * np.sqrt(diag_cov_matrix[i]), 0.000001), min(flat_conf_matrix[i] + 3 * np.sqrt(diag_cov_matrix[i]), 0.999999))) ### defining bounds as +- 3*sigma around the average conf_matrix value, but also taking min as 0, and max as 1\r\n\r\n\r\nglobal signal\r\n\r\nglobal obs_array \r\n\r\nglobal scale\r\n\r\n#scale = pow((1.1/10000),36)\r\nscale = 1\r\n\r\n###obs_array = [13, 19, 24, 19, 16, 9]\r\n\r\nobs_array = genfromtxt('C:\\\\Users\\\\jacgwatkins\\\\Data\\\\predicitonsMC_xc_done\\\\total100_obs10k\\\\xc_signal0.1_obs10k.txt')[100]\r\n\r\n\r\n\r\n\r\n\r\n\r\n### obs_array, signal defined globally in the \"secondary\" functions built from these 'primary' ones\r\n\t\r\ndef NLL(combined_array): ### combined vector of the 6 probabilities, and the 36 matrix parameters (representing action of the algorithm on x_true (not its inverse, so we can impose the conditions in minimization) in a signle run) flattened, 42 in total, \t\t\r\n \t\t\t\t\t ### takes in the input this way, because the minimization function calls needs to be a flattened vector of the parameters\r\n \r\n \r\n ### trying different initalization for probs and flat aglorithm matrix mathod so I don't touch the array returnd from the minimization in case it affects how it works:\r\n \r\n probs_array = np.zeros(6)\r\n algorithm_matrix_flat = np.zeros(36)\r\n \r\n for i in range(6):\r\n probs_array[i] = combined_array[i]\r\n \r\n for i in np.arange(6,42):\r\n algorithm_matrix_flat[i-6] = combined_array[i]\r\n \r\n \r\n \r\n \r\n global gcounter\r\n \r\n gcounter += 1\r\n \r\n# temp_array = np.split(combined_array, [6]) ### splits input into 2 vectors, from 0 to 5 the probs vector, and the remaining 36 the flattened algorithm matrix (the r vector) \r\n \t\r\n# probs_array = temp_array[0]\r\n\t \r\n# algorithm_matrix_flat = temp_array[1]\r\n \r\n algorithm_matrix = np.reshape(algorithm_matrix_flat, (6,6))\r\n \r\n algorithm_matrix = np.transpose(algorithm_matrix) ### conf_matrix already tansposed before saving, so no need to redo\r\n\r\n# print ('algorithm matrix \\n', algorithm_matrix, '\\n') \r\n\r\n r_matrix = np.linalg.inv(algorithm_matrix)\t\t\t\t### inverse of matrix representing the action of matrix on particular obs array, to be found by minimization\r\n# \t\r\n r_array = r_matrix.flatten()\r\n \r\n \r\n \r\n \t## 1st term in NLL:\r\n first_term = math.log(abs(np.linalg.det(algorithm_matrix)))\r\n\t\r\n\t\r\n\t## 2nd term in NLL \r\n outer_sum = 0\r\n for i in range(6):\r\n inner_sum = 0\r\n\t\t\r\n for j in range(6):\r\n\t\t\t\r\n inner_sum += (r_matrix[i][j] * obs_array[j])\r\n\t\t\t \r\n outer_sum += inner_sum * math.log(probs_array[i])\r\n\t\t\t\t\t\t\r\n second_term = (-1) * outer_sum\r\n\r\n\r\n\t## 3rd term in NLL:\r\n outer_sum = 0\r\n for m in range(6):\r\n inner_sum = 0\r\n\t\t\r\n for n in range(6):\r\n\t\t\t\r\n inner_sum += (r_matrix[m][n] * obs_array[n])\r\n \r\n \r\n bracket_value = gamma(inner_sum + 1)\r\n \r\n try: \r\n \r\n outer_sum += math.log( bracket_value ) ## +1 because gamma(n) = (n-1)!\r\n\t\t\r\n except:\r\n print ('ERROR!!!!!!')\r\n print ('counter: ', gcounter, '\\n')\r\n print ('obs_array: ', obs_array, '\\n')\r\n print ('prob minima \\n', probs_array, '\\n')\r\n print ('algorithm_matrix; \\n', algorithm_matrix, '\\n')\r\n print ('conf_matrix \\n', conf_matrix, '\\n')\r\n print ('inverse r matrix: \\n', r_matrix, '\\n')\r\n print ('multiplication of determinants: ', np.linalg.det(algorithm_matrix) * np.linalg.det(r_matrix), '\\n')\r\n print ('first term is ', first_term, '\\n')\r\n print ('second term is ', second_term, '\\n')\r\n print ('inv cov matrix \\n' , inv_cov_matrix, '\\n')\r\n err_matrix = np.zeros((6,6))\r\n cov_matrix_diag_new = np.zeros((6,6))\r\n \r\n for i in range(6):\r\n for j in range(6):\r\n cov_matrix_element = np.sqrt(cov_matrix[i*6+j][i*6+j])\r\n cov_matrix_diag_new[i][j] = cov_matrix_element\r\n err_matrix[i][j] = (algorithm_matrix[i][j] - conf_matrix[i][j])/cov_matrix_element\r\n \r\n print ('cov_matrix_diag \\n', cov_matrix_diag_new, '\\n') \r\n \r\n print ('err_matrix \\n', err_matrix, '\\n')\r\n \r\n for i in range(6):\r\n print ('sum of column ', i, 'is ', sum(algorithm_matrix[:,i]), '\\n')\r\n \r\n \r\n for i in range(6):\r\n print ('number of predicted events of type ', i, 'is ' , np.dot(r_matrix[i], obs_array), '\\n')\r\n \r\n print ('sum of probs ', sum(combined_array[0:6]), '\\n')\r\n \r\n \r\n print ('press to continue')\r\n \r\n if abs(sum(combined_array[0:6])-1) > 0.01 or abs(sum(combined_array[6:12])-1) > 0.01 or abs(sum(combined_array[12:18])-1) > 0.01 or abs(sum(combined_array[18:24])-1) > 0.01 or abs(sum(combined_array[24:30])-1) > 0.01 or abs(sum(combined_array[30:36])-1) > 0.01 or abs(sum(combined_array[36:42])-1) > 0.01:\r\n print ('sum to 1 constraints not respected')\r\n print ('press to continue \\n')\r\n \r\n print ('sum of probs ', sum(combined_array[0:6]), '\\n')\r\n print ('sum first 6 Pij ', sum(combined_array[6:12]), '\\n')\r\n print ('sum second 6 Pij ', sum(combined_array[12:18]), '\\n')\r\n print ('sum third 6 Pij ', sum(combined_array[18:24]), '\\n')\r\n print ('sum fourth 6 Pij ', sum(combined_array[24:30]), '\\n')\r\n print ('sum fifth 6 Pij ', sum(combined_array[30:36]), '\\n')\r\n print ('sum sixth 6 Pij ', sum(combined_array[36:42]), '\\n')\r\n \r\n print ('-------------------------------------------')\r\n \r\n x = input()\r\n\r\n return 1000\r\n \r\n \r\n third_term = outer_sum\r\n\t\t\r\n\t\t\r\n\t## 4th term in NLL:\r\n deviation_array = r_array - avg_array\t\t\t## deviation from the average\r\n\t\r\n temp_fourth_term = np.dot(inv_cov_matrix, deviation_array)\r\n\t\r\n fourth_term = np.dot(deviation_array, temp_fourth_term)\r\n\t\r\n fourth_term = 0.5 * scale * fourth_term\r\n \t\r\n value = first_term + second_term + third_term + fourth_term\r\n \r\n \r\n \r\n if gcounter%100 == 0:\r\n \r\n print ('obs_array: ', obs_array, '\\n')\r\n print ('prob minima \\n', probs_array, '\\n')\r\n print ('algorithm_matrix; \\n', algorithm_matrix, '\\n')\r\n print ('conf_matrix \\n', conf_matrix, '\\n')\r\n print ('inverse conf: \\n', r_matrix, '\\n')\r\n print ('NLL value: \\n', value, '\\n')\r\n print ('first term is ', first_term, '\\n')\r\n print ('second term is ', second_term, '\\n')\r\n print ('third term is ', third_term, '\\n')\r\n print ('fourth term is ', fourth_term, '\\n')\r\n print ('temp fourth term ', temp_fourth_term, '\\n')\r\n print ('inv cov matrix \\n' , inv_cov_matrix, '\\n')\r\n print ('deviation array \\n', deviation_array, '\\n')\r\n err_matrix = np.zeros((6,6))\r\n cov_matrix_diag_new = np.zeros((6,6))\r\n \r\n for i in range(6):\r\n for j in range(6):\r\n cov_matrix_element = np.sqrt(cov_matrix[i*6+j][i*6+j])\r\n cov_matrix_diag_new[i][j] = cov_matrix_element\r\n err_matrix[i][j] = (algorithm_matrix[i][j] - conf_matrix[i][j])/cov_matrix_element\r\n \r\n print ('cov_matrix_diag \\n', cov_matrix_diag_new, '\\n') \r\n \r\n print ('err_matrix \\n', err_matrix, '\\n')\r\n \r\n for i in range(6):\r\n print ('sum of column ', i, 'is ', sum(algorithm_matrix[:,i]), '\\n')\r\n \r\n \r\n for i in range(6):\r\n print ('number of predicted events of type ', i, 'is ' , np.dot(r_matrix[i], obs_array), '\\n')\r\n \r\n \r\n print ('counter: ', gcounter, '\\n')\r\n \r\n print ('-------------------------------------------')\r\n \r\n print ('space to continue')\r\n \r\n x = input()\r\n \r\n \t\r\n \r\n if abs(sum(combined_array[0:6])-1) > 0.01 or abs(sum(combined_array[6:12])-1) > 0.01 or abs(sum(combined_array[12:18])-1) > 0.01 or abs(sum(combined_array[18:24])-1) > 0.01 or abs(sum(combined_array[24:30])-1) > 0.01 or abs(sum(combined_array[30:36])-1) > 0.01 or abs(sum(combined_array[36:42])-1) > 0.01:\r\n print ('sum to 1 constraints not respected')\r\n print ('press to continue')\r\n \r\n print ('sum of probs ', sum(combined_array[0:6]), '\\n')\r\n print ('sum first 6 Pij ', sum(combined_array[6:12]), '\\n')\r\n print ('sum second 6 Pij ', sum(combined_array[12:18]), '\\n')\r\n print ('sum third 6 Pij ', sum(combined_array[18:24]), '\\n')\r\n print ('sum fourth 6 Pij ', sum(combined_array[24:30]), '\\n')\r\n print ('sum fifth 6 Pij ', sum(combined_array[30:36]), '\\n')\r\n print ('sum sixth 6 Pij ', sum(combined_array[36:42]), '\\n')\r\n \r\n print ('-------------------------------------------')\r\n \r\n x = input()\r\n\r\n \r\n return value\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n#def NLL2(combined_array):\t\t\t### same as NLL function but with fixed signal parameter, 41 parameters to be minimized in total, \r\n#\t\t\t\t\t\t\t\t\t### the first five elements of the combined_array are the background probabilities, then 36 algorithm matrix elements flattened\r\n#\t\r\n#\t\r\n# temp_array = np.split(combined_array, [5]) ### splits input into 2 vectors, from 0 to 4 the bkgrnd probs vector, and the remaining 36 the flattened algorithm matrix (the r vector)\r\n#\t\r\n# probs_array = temp_array[0] \r\n#\t\r\n# probs_array = np.insert(probs_array, 0, signal, axis = 0) \t\t### adds signal to the beginning of the obs_array, so the calculations can be performed as before, also signal is set outside in the secondary fucntions\r\n#\t\r\n# algorithm_matrix_flat = temp_array[1] ### matrix representing algorithm (flattened) action on true vector to give classified vector\r\n#\t \r\n# algorithm_matrix = np.reshape(algorithm_matrix_flat, (6,6))\r\n# \r\n# algorithm_matrix = np.transpose(algorithm_matrix)\t\r\n# \r\n# r_matrix = np.linalg.inv(algorithm_matrix)\t\t\t\t### matrix representing the action of matrix on particular obs array, to be found by minimization\r\n# \t\r\n# r_array = r_matrix.flatten()\r\n# \r\n# \t## 1st term in NLL:\r\n# first_term = np.linalg.det(algorithm_matrix)\r\n#\t\r\n#\t\r\n#\t## 2nd term in NLL:\r\n# outer_sum = 0\r\n# for i in range(6):\r\n# inner_sum = 0\r\n#\t\t\r\n# for j in range(6):\r\n#\t\t\t\r\n# inner_sum += (r_matrix[i][j] * obs_array[j])\r\n#\t\t\t \r\n# outer_sum += inner_sum * math.log(probs_array[i])\r\n#\t\t\t\t\t\t\r\n# second_term = (-1) * outer_sum\r\n#\r\n#\r\n#\t## 3rd term in NLL:\r\n# outer_sum = 0\r\n# for m in range(6):\r\n# inner_sum = 0\r\n#\t\t\r\n# for n in range(6):\r\n#\t\t\t\r\n# inner_sum += (r_matrix[m][n] * obs_array[n])\r\n#\t\t\r\n# outer_sum += math.log( gamma(inner_sum + 1) ) ## +1 because gamma(n) = (n-1)!\r\n#\t\t\r\n# third_term = outer_sum\r\n#\t\t\r\n#\t\t\r\n#\t## 4th term in NLL:\r\n# deviation_array = r_array - avg_array\t\t\t## deviation from the average\r\n#\t\r\n# fourth_term = np.dot(inv_cov_matrix, deviation_array)\r\n#\t\r\n# fourth_term = np.dot(deviation_array, fourth_term)\r\n#\t\r\n# fourth_term = 0.5 * fourth_term\r\n#\t\r\n# \r\n# return first_term + second_term + third_term + fourth_term\r\n#\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n### easier to keep the top two funcs separated for the purpose of defining constraints in minimization \t\r\n\t\r\n\t \r\n\t\r\ndef NLL_minimize(function): ### the function passed is the one to be minimized, checks for which function it is and adjusts minimization conditions accordingly\r\n\t\r\n global gcounter\r\n \r\n gcounter = 0\r\n \r\n checker = True\r\n\t \r\n if function == NLL:\r\n \r\n \r\n while checker == True: ### repeates and checker becomes False, as long as its True it will repeat\r\n \r\n \r\n# try:\r\n# x0 =np.random.uniform(0.01, 1, 6) \t\t### initializing probablities between 0 and 1, and below initializing matrix elements to the average confmatrix elements\r\n\t\t\t###################\r\n x0 = (1/6) * np.ones(6)\r\n \r\n# for i in range(6):\r\n# x0[i] = np.random.uniform(0, 1 - sum(x0))\r\n \r\n \r\n \r\n ####################\r\n# elements_init = np.zeros(36)\r\n# \r\n# for k in range(36):\r\n# elements_init[k] = np.random.uniform(bnd[k][0], bnd[k][1])\r\n# \r\n# \r\n# x0 = np.append(x0, elements_init)\r\n# ###########################\r\n\r\n\r\n x0 = np.append(x0, flat_conf_matrix) \r\n\t\t\t\r\n \r\n \r\n \r\n \r\n# bnd = [(0.799,0.823),(0.051,0.059),(0.007,0.015),(0.064,0.08),(0.032,0.04),(0.011,0.019),(0.045,0.069),(0.785,0.817),(0.0017,0.0033),(0,0.00063),(0.127,0.151),(0,0.0007),(0.034,0.05),(0.0006,0.0086),(0.709,0.741),(0.092,0.116),(0.108,0.14),(0,0.0007),(0.135,0.167),(0.036,0.052),(0.146,0.178),(0.472,0.512),(0.07,0.086),(0.061,0.085),(0.093,0.117),(0.201,0.233),(0.167,0.191),(0.0352,0.0528),(0.446,0.486),(0,0.025),(0.208,0.24),(0.13,0.162),(0.0125,0.0285),(0.103,0.135),(0.06,0.084),(0.399,0.439)]\r\n \r\n \r\n prob_bnd = (10**(-4), 1 - 10**(-4))\r\n bounds = (prob_bnd, prob_bnd, prob_bnd, prob_bnd, prob_bnd, prob_bnd, bnd[0], bnd[1], bnd[2], bnd[3], bnd[4], bnd[5], bnd[6], bnd[7], bnd[8], bnd[9], bnd[10], bnd[11], bnd[12], bnd[13], bnd[14], bnd[15], bnd[16], bnd[17], bnd[18], bnd[19], bnd[20], bnd[21], bnd[22], bnd[23], bnd[24], bnd[25], bnd[26], bnd[27], bnd[28], bnd[29], bnd[30], bnd[31], bnd[32], bnd[33], bnd[34], bnd[35]) \r\n\t\t\t\r\n eq_cons = {'type': 'eq', 'fun' : lambda x: np.array([x[0] + x[1] + x[2] + x[3] + x[4] + x[5] - 1, x[6] + x[7] + x[8] + x[9] + x[10] + x[11] - 1, x[12] + x[13] + x[14] + x[15] + x[16] + x[17] - 1, x[18] + x[19] + x[20] + x[21] + x[22] + x[23] - 1, x[24] + x[25] + x[26] + x[27] + x[28] + x[29] - 1, x[30] + x[31] + x[32] + x[33] + x[34] + x[35] - 1, x[36] + x[37] + x[38] + x[39] + x[40] + x[41] - 1])} \t ### equality constraint for SLSQP algorithm, the sum of probabilities (first 6) have has to be 1, then every following 6 (which a a matrix row) have to sum to 6\r\n\t\t\t\r\n\t\t\t\t\t\r\n res = minimize(function, x0, method='SLSQP', options={'ftol': 1e-10}, constraints = [eq_cons], bounds = bounds) \r\n\t\t\t\r\n\t\t\t\r\n minimization_res = res.x\r\n\t\t\t\r\n \r\n if abs(sum(minimization_res[0:6])-1) > 0.01 or abs(sum(minimization_res[6:12])-1) > 0.01 or abs(sum(minimization_res[12:18])-1) > 0.01 or abs(sum(minimization_res[18:24])-1) > 0.01 or abs(sum(minimization_res[24:30])-1) > 0.01 or abs(sum(minimization_res[30:36])-1) > 0.01 or abs(sum(minimization_res[36:42])-1) > 0.01:\r\n checker = True\r\n print ('sum is incorrect')\r\n else:\r\n checker = False\r\n \r\n \r\n# counter += 1\r\n# if counter > 50:\r\n# checker = False ## so doesn't loop for too long\r\n# \r\n# except:\r\n# checker = True\r\n\r\n# print (minimization_res)\r\n# elif function == NLL2:\r\n#\t\r\n# while checker == True: ### repeates and checker becomes False, as long as its True it will repeat\r\n#\t\t\r\n#\t\t\t\r\n# x0 =np.random.uniform(0, 1-signal, 41) \t\t### 41 is no. of parameters to be minimized in NLL2 (with fixed signal)\r\n#\t\t\t\r\n#\t\t\t\r\n# bnd = (0,1) \t\t\t\t\t\t\t\t### here bound for probabilities is 0 to 1-signal, but matrix elements is still 0 to 1 \r\n# prob_bnd2 = (0.001, 1 - signal)\r\n#\t\t\t\r\n# bounds = (prob_bnd2, prob_bnd2, prob_bnd2, prob_bnd2, prob_bnd2, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd, bnd) \r\n#\t\t\t\r\n# eq_cons = {'type': 'eq', 'fun' : lambda x: np.array([x[0] + x[1] + x[2] + x[3] + x[4] + x[5] - (1 - signal), x[6] + x[7] + x[8] + x[9] + x[10] + x[11] - 1, x[12] + x[13] + x[14] + x[15] + x[16] + x[17] - 1, x[18] + x[19] + x[20] + x[21] + x[22] + x[23] - 1, x[24] + x[25] + x[26] + x[27] + x[28] + x[29] - 1, x[30] + x[31] + x[32] + x[33] + x[34] + x[35] - 1, x[36] + x[37] + x[38] + x[39] + x[40] + x[41] - 1])} \t ### double check, is the matrix element corresponding to signal floating or fixed, because if it is fixed, this will change the constraint on matrix element, I'm almost certain it floats, and conditions are the same as above\r\n#\t\t\t\r\n#\t\t\t\t\t\r\n# res = minimize(function, x0, method='SLSQP', options={'ftol': 1e-30}, constraints = [eq_cons], bounds = bounds) ## check if htis works w/o defining the jacobian\r\n#\t\t\t\r\n# \r\n# minimization_res = res.x\r\n#\t\t\t\r\n#\r\n#\r\n# if isinstance(minimization_res[0], complex) or isinstance(minimization_res[1], complex) or isinstance(minimization_res[2], complex) or isinstance(minimization_res[3], complex) or isinstance(minimization_res[4], complex) or isinstance(minimization_res[5], complex):\r\n# checker = True ###checking to see if there are any complex values, to repeat htis step, till all of them aren't complex\r\n# elif minimization_res[0] <= 0 or minimization_res[1] <= 0 or minimization_res[2] <= 0 or minimization_res[3] <= 0 or minimization_res[4] <= 0 or minimization_res[5] <= 0 :\r\n# checker = True ### all need to be +ve, for checker to become False and the while loop to terminate, and move on ot next input vector, if any are negative, iteration repeats\r\n## elif abs(np.sum(minimization_res) - 1) > 0.09: ###checking sum is correct\r\n## checker = True\r\n# else:\r\n# checker = False\t\r\n\t\r\n\t\r\n\t\r\n \r\n return minimization_res\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n### didn't end up using this, but leave it for now:\t\t\t\t\r\n\t\t\r\n\t\t\r\ndef new_folder(dir_name):\t\t\t\t\t\t\t\t\t\t\t\t\t### function to create new folder, checks if folder name already exists first\r\n\r\n if not os.path.exists(dir_name):\r\n os.mkdir(dir_name)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n else:\r\n print('folder already exists')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#def NLLshort(combined_array):\r\n# \r\n# temp_array = np.split(combined_array, [6]) ### splits input into 2 vectors, from 0 to 5 the probs vector, and the remaining 36 the flattened algorithm matrix (the r vector) \r\n# \t\t \r\n# algorithm_matrix_flat = temp_array[1]\r\n# \r\n# algorithm_matrix = np.reshape(algorithm_matrix_flat, (6,6))\r\n# \r\n# algorithm_matrix = np.transpose(algorithm_matrix) ### conf_matrix already tansposed before saving, so no need to redo\r\n# \r\n# r_matrix = np.linalg.inv(algorithm_matrix)\t\t\t\t### inverse of matrix representing the action of matrix on particular obs array, to be found by minimization\r\n## \t\r\n# r_array = r_matrix.flatten()\r\n#\r\n#\r\n#\t## 4th term in NLL:\r\n# deviation_array = r_array - avg_array\t\t\t## deviation from the average\r\n#\t\r\n# fourth_term = np.dot(inv_cov_matrix, deviation_array)\r\n#\t\r\n# fourth_term = np.dot(deviation_array, fourth_term)\r\n#\t\r\n# fourth_term = 0.5 * fourth_term\r\n#\t\r\n#\t\r\n#\t\r\n# return fourth_term\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n### SECONDARY functions, the function to get the NLL profile points, and function to get minima is defined using the 4 primary functions\r\n\r\n\r\ndef NLL_profile_points(obs):\t\t\t\t\t\t\t\t\t### arrays get saved to a new folder inside the output path passed\r\n \r\n obs_array = obs\r\n\t\r\n n_inc = 50 \r\n\t\r\n signal_vals = []\r\n NLL_vals = []\r\n\t\r\n predictions = NLL_minimize(NLL)\r\n\t\r\n signal = predictions[0]\r\n\t\r\n original_NLL = NLL(predictions)\r\n\t\r\n signal_vals.append(signal)\r\n NLL_vals.append(original_NLL)\r\n\t\r\n\t\r\n positive_inc = (1-signal)/n_inc\r\n\t\r\n for i in range(n_inc):\r\n\t\t\r\n signal += positive_inc\r\n\t\t\r\n\t\t\r\n predictions2 = NLL_minimize(NLL2) ### background and matrix elements minima (excluding singal probability)\r\n\t\t\r\n\t\t\r\n signal_vals.append(signal)\r\n NLL_vals.append(NLL2(predictions2))\r\n\t\t\r\n\t\t\r\n if i > 5:\r\n break \r\n \r\n if NLL2(predictions2) > (original_NLL + 1):\r\n if NLL2(predictions2) > (original_NLL + 4):\r\n n_inc = 500\r\n \r\n else:\r\n break\r\n\t\t\t\t\r\n\t\r\n\r\n\r\n\r\n signal = predictions[0]\r\n\t\r\n negative_inc = signal/n_inc\r\n\t\r\n for k in range(n_inc):\r\n\t\t\r\n signal -= negative_inc\r\n\t\t\r\n predictions2 = NLL_minimize(NLL2)\r\n\t\t\r\n\t\t\r\n signal_vals.append(signal)\r\n NLL_vals.append(NLL2(predictions2))\r\n\t\t\r\n if i > 5:\r\n break \r\n \r\n if NLL2(predictions2) > (original_NLL + 1):\r\n if NLL2(predictions2) > (original_NLL + 4):\r\n n_inc = 500\r\n \r\n else:\r\n break\r\n\t\r\n\r\n arrays = np.vstack((signal_vals, NLL_vals))\r\n return arrays\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\ndef get_profiles(obs_path, output_path, n_events, true_signal): \t\t\t\t\t### input path is the obs file organized in 6 columns for each event type, the output path is the folder to save the outputs, nevents is the no. of events in each observation vector\r\n\t\r\n print ('start time is: ', datetime.datetime.now())\r\n\t\r\n obs_file = genfromtxt(obs_path)\r\n\t\r\n output_path = output_path + '\\\\signal' + str(true_signal) + '_events' + str(n_events) + '_signal_NLL_arrays'\r\n\t\r\n new_folder(output_path)\r\n\t\r\n for row_index in range(len(obs_file)):\r\n\t\t\r\n global obs_array\r\n \r\n obs_array = obs_file[row_index, :]\r\n\t\t\r\n current_output_path = output_path + '\\\\signal_NLL_arrays' + str(row_index + 1) + '_TrueSig' + str(true_signal) + '_TotalEvents' + str(n_events) + '.txt'\r\n\t\t\r\n current_arrays_file = NLL_profile_points(obs_array)\r\n\t\t\r\n np.savetxt(current_output_path, current_arrays_file)\r\n\t\t\r\n\t\t\r\n print ('end time is: ', datetime.datetime.now())\r\n\t\r\n\t\r\n\t\r\n\t\r\ndef get_obs_minima(obs_path, output_path, n_events, true_signal):\t\t\t\t### input paths is the obs file same as above, output path is where the matrix len(obs_file)x42 (saving all 6 probabs, and the 36 parameters) is going to be saved, becasue easier to save this to the same file, where for profiels, easier to save NLL/singal arrays of each obs to a separate profile, due to varying lengths between each\r\n\t\r\n print ('start time is: ', datetime.datetime.now())\r\n\t\r\n output_path = output_path + '\\\\signal' + str(true_signal) + '_events' + str(n_events) + '_NLL_minima'\r\n\t\r\n new_folder(output_path)\r\n\t\r\n output_path = output_path + '\\\\Test5_TrueSig_' + str(true_signal) + '_totalEvents_' + str(n_events) + '_minima.txt'\r\n\t\r\n obs_file = genfromtxt(obs_path)\r\n\t\r\n minima_file = np.zeros(42) \t## just a place holder to enable use of vstack fucntion below\r\n\t\r\n \r\n for row_index in range(len(obs_file)):\r\n \r\n global obs_array\r\n \r\n obs_array = obs_file[row_index, :]\r\n\t\t\r\n# try:\r\n \r\n current_minima = NLL_minimize(NLL)\r\n \r\n# current_minima = np.append(current_minima , NLL(current_minima))\r\n\t\t\r\n minima_file = np.vstack((minima_file, current_minima))\r\n\t\t\r\n print (row_index, ' is done')\r\n \t\r\n ## for testing:\r\n \r\n# except:\r\n# print('error')\r\n \r\n# continue\r\n\t\t\r\n if row_index > 100:\r\n break\r\n\t\t\r\n \r\n minima_file = minima_file[1:,:]\t\t\t### getting rid of the placeholder zeros row\r\n\t\r\n np.savetxt(output_path, minima_file)\r\n\t\r\n print ('end time is: ', datetime.datetime.now())\r\n \r\n \r\n ###################################################################\r\n \r\nNLLs = []\r\n \r\nfor h in range(100):\r\n# try:\r\n NLLs.append(NLL(NLL_minimize(NLL)))\r\n# except:\r\n# print('error')\r\n# continue\r\n \r\nprint (len(NLLs))\r\nprint (NLLs) \r\n \r\nhist, bin_edges = np.histogram(NLLs, density=True)\r\n\r\nbin_centres = (bin_edges[:-1] + bin_edges[1:])/2\r\n\r\nplt.plot(bin_centres, hist)","sub_path":"with_test_secondary_funcs.py","file_name":"with_test_secondary_funcs.py","file_ext":"py","file_size_in_byte":26101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"440907547","text":"import csv\n \nimport cx_Oracle\n \nconnection = cx_Oracle.connect(\"SYSTEM\", \"12345\", \"localhost:1521/xe\")\n\ncursor_fb_news = connection.cursor()\n \ncursor_fb_news.execute(\"\"\"\nSELECT\n TRIM(fact_name) as fact_name,\n TRIM(new_id) as new_id\nFROM\n fb_news\"\"\")\n \nfor new_id, fact_name in cursor_fb_news:\n \n with open(\"fb_new_\"+new_id+\".csv\", \"w\", newline=\"\") as file:\n writer = csv.writer(file)\n \n writer.writerow([\"Number\", new_id])\n writer.writerow([\"Name\", fact_name])\n \n cursor_facts = connection.cursor()\n \n query = \"\"\"\n SELECT DISTINCT\n fact_name,\n fact_date,\n \n FROM\n fb_new NATURAL JOIN facts\n Where TRIM(new_id_fk_ds) = :id\"\"\"\n \n cursor_facts.execute(query, id = new_id)\n writer.writerow([])\n writer.writerow([\"New topic\", \"New date\"])\n for facts_row in cursor_facts:\n print(facts_row)\n writer.writerow(facts_row)\n \ncursor_facts.close()\n","sub_path":"km63/Miliev_Maksym/csv_export.py","file_name":"csv_export.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"175148559","text":"\"\"\"\nClass for connecting to remote servers via SSH and get their\nconsumption information.\n\n* Author: Andrés Arias\n* Email: andres.arias12@gmail.com\n\"\"\"\n\nimport paramiko\nimport click\n\nclass Server:\n \"\"\"\n Connects to a remote server via SSH. Can use password or PEM keys for\n authentication.\n\n Parameters\n ----------\n ip_address: string\n IPv4 address of the remote server.\n username: string\n Username to log into via SSH.\n creds: string\n PEM key path to use for SSH authentication.\n timeout: int\n Time in seconds to wait before giving up trying to connected.\n\n Attributes\n ----------\n ip_address: string\n IPv4 address of the remote server.\n username: string\n Username to log into via SSH.\n credentials: string\n PEM key path to use for SSH authentication.\n timeout: int\n Time in seconds to wait before giving up trying to connected.\n connected: bool\n Indicates if a connection is currently established or not\n \"\"\"\n\n connected = False\n \"\"\"\n bool: Indicates if a connection is currently established or not.\n \"\"\"\n\n def __init__(self, ip_address, username, creds, timeout=60):\n self.ip_address = ip_address\n self.username = username\n self.client = paramiko.SSHClient()\n self.timeout = timeout\n self.credentials = paramiko.RSAKey.from_private_key_file(creds)\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n def connect(self):\n \"\"\"\n Establishes a connection via SSH to the remote server using\n the parameters provided when initializing the Server object.\n\n Raises\n ------\n Exception\n If connection times out or server not found.\n \"\"\"\n self.client.connect(hostname=self.ip_address,\n username=self.username,\n pkey=self.credentials,\n timeout=self.timeout)\n click.echo(\"Succesfully logged into address %s\" % self.ip_address)\n self.connected = True\n\n def disconnect(self):\n \"\"\"\n Establishes a connection via SSH to the remote server using\n the parameters provided when initializing the Server object.\n \"\"\"\n if self.connected:\n self.client.close()\n\n def get_running_proccesses(self):\n \"\"\"\n Queries the server for the currently running processes (one interval) and\n returns a list with the processes names.\n\n Returns\n -------\n list\n A list containing strings with the name of every running processes\n on the server.\n\n \"\"\"\n stdin, stdout, stderr = self.client.exec_command('ps axco command --sort=-pcpu')\n process_list = []\n process_list_raw = stdout.readlines()\n process_list_raw.pop(0)\n for proc in process_list_raw:\n process_list.append(proc.rstrip())\n return process_list\n\n\n def get_top_cpu(self):\n \"\"\"\n Queries the server for the currently running processes (one interval) and\n returns a dictionary containing the top 3 processes consuming CPU.\n\n Returns\n -------\n dictionary\n A dictionary containing the top 3 processes consuming CPU, where the\n keys are de process names and the value the consumed CPU percentage.\n\n \"\"\"\n stdin, stdout, stderr = self.client.exec_command('ps axco command,pcpu --sort=-pcpu | head -n 4')\n output_lines = stdout.readlines()\n line_count = len(output_lines)\n # Sometimes the command only returns 2 processes instead of 3, re-running\n # the command fixes it:\n while line_count != 4:\n stdin, stdout, stderr = self.client.exec_command('ps axco command,pcpu --sort=-pcpu | head -n 4')\n output_lines = stdout.readlines()\n line_count = len(output_lines)\n return self.__clean_stdout(output_lines)\n\n\n def get_top_mem(self):\n \"\"\"\n Queries the server for the currently running processes (one interval) and\n returns a dictionary containing the top 3 processes consuming memory.\n\n Returns\n -------\n dictionary\n A dictionary containing the top 3 processes consuming memory, where the\n keys are de process names and the value the consumed memory percentage.\n\n \"\"\"\n stdin, stdout, stderr = self.client.exec_command('ps axco command,pmem --sort=-pmem | head -n 4')\n output_lines = stdout.readlines()\n return self.__clean_stdout(output_lines)\n\n\n def __clean_stdout(self, output_lines):\n process_dict = {}\n output_lines.pop(0)\n for proc in output_lines:\n split_list = proc.split(' ')\n clean_list = []\n for i in split_list:\n if i != '':\n clean_list.append(i.rstrip())\n process_dict[clean_list[0]] = float(clean_list[1])\n return process_dict\n\n\n def get_remaining_cap(self):\n \"\"\"\n Queries the server for the current CPU and memory usage and returns\n the remaining CPU percentage and memory in kB available.\n\n Returns\n -------\n dictionary\n A dictionary where the ``cpu`` key indicates the remaining CPU\n percentage available and the ``memory_kb`` key indicates the\n remaining memory in kB.\n\n \"\"\"\n result_dict = {}\n stdin, stdout, stderr = self.client.exec_command('grep \\'cpu \\' /proc/stat | awk \\'{usage=($2+$4)*100/($2+$4+$5)} END {print usage}\\'')\n total_cpu = stdout.readlines()[0].rstrip()\n remaining_cpu = (1 - float(total_cpu)) * 100\n result_dict['cpu'] = remaining_cpu\n stdin, stdout, stderr = self.client.exec_command('cat /proc/meminfo | grep MemAvailable')\n split_list = stdout.readlines()[0].split(' ')\n clean_list = []\n for i in split_list:\n if i != '':\n clean_list.append(i.rstrip())\n result_dict['memory_kb'] = int(clean_list[1])\n return result_dict\n\n","sub_path":"vmdiag/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"264929417","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom sfeprapy.dat.steel_carbon import steel_specific_heat_carbon_steel\nfrom sfeprapy.func.fire_iso834 import fire as _fire_iso\nfrom sfeprapy.func.fire_parametric_ec import fire as _fire_param\nfrom sfeprapy.func.fire_travelling import fire as _fire_travelling\nfrom sfeprapy.func.heat_transfer_protected_steel_ec import protected_steel_eurocode as _steel_heat_transfer\n\n\ndef fire_param(ax, label=None):\n\n x = np.arange(0, 60*180, 1, dtype=float)\n\n # PARAMETRIC FIRE\n inputs = {\n \"t\": x,\n \"A_t\": (10*40+40*2+2*10)*2,\n \"A_f\": 10*40,\n \"A_v\": 5*5,\n \"h_eq\": 5,\n \"q_fd\": 420e6,\n \"lambda_\": 1,\n \"rho\": 1,\n \"c\": 2250000,\n \"t_lim\": 20 * 60,\n \"temperature_initial\": 273.15\n }\n y = _fire_param(**inputs)\n\n ax.plot(x/60., y-273.15, label=label)\n\n\ndef fire_travel(ax, label=None):\n x = np.arange(0, 60*180, 1, dtype=float)\n\n inputs = {\n \"t\": x,\n \"T_0\": 273.15,\n \"q_fd\": 420e6,\n \"RHRf\": 0.15e6,\n \"l\": 40,\n \"w\": 10,\n \"s\": 0.01,\n \"h_s\": 4.5,\n \"l_s\": 25,\n }\n y = _fire_travelling(**inputs)\n\n ax.plot(x/60., y-273.15, label=label)\n\n\ndef heat_transfer_param(ax, label=None):\n\n x = np.arange(0, 60*180, 1, dtype=float)\n\n # PARAMETRIC FIRE\n inputs_parametric_fire = {\n \"t\": x,\n \"A_t\": 360,\n \"A_f\": 100,\n \"A_v\": 21.6,\n \"h_eq\": 1,\n \"q_fd\": 600e6,\n \"lambda_\": 1,\n \"rho\": 1,\n \"c\": 2250000,\n \"t_lim\": 20 * 60,\n \"temperature_initial\": 273.15\n }\n y_ = _fire_param(**inputs_parametric_fire)\n\n # steel_prop = Thermal()\n\n _, y, _ = _steel_heat_transfer(\n time=x,\n temperature_ambient=y_,\n rho_steel=7850,\n # c_steel_T=steel_specific_heat_carbon_steel,\n area_steel_section=0.017,\n k_protection=0.2,\n rho_protection=800,\n c_protection=1700,\n thickness_protection=0.00938,\n perimeter_protected=2.14,\n # is_terminate_peak=False\n )\n\n ax.plot(x/60., y-273.15, label=label)\n\n\ndef heat_transfer_travel(ax, label=None):\n\n x = np.arange(0, 60*180, 1, dtype=float)\n\n inputs = {\n \"t\": x,\n \"T_0\": 273.15,\n \"q_fd\": 420e6,\n \"RHRf\": 0.15e6,\n \"l\": 40,\n \"w\": 10,\n \"s\": 0.01,\n \"h_s\": 4.5,\n \"l_s\": 25,\n }\n y_ = _fire_travelling(**inputs)\n\n # steel_prop = Thermal()\n\n _, y, _ = _steel_heat_transfer(\n time=x,\n temperature_ambient=y_,\n rho_steel=7850,\n # c_steel_T=steel_prop.c(),\n area_steel_section=0.017,\n k_protection=0.2,\n rho_protection=800,\n c_protection=1700,\n thickness_protection=0.00938,\n perimeter_protected=2.14,\n # is_terminate_peak=False\n )\n\n ax.plot(x/60., y-273.15, label=label)\n\n\ndef fire_iso834(ax, label=None):\n\n x = np.arange(0, 60*180, 1)\n y = _fire_iso(x, 20 + 273.15)\n\n ax.plot(x/60., y-273.15, label=label)\n\n\ndef plot_examples(list_func, list_linelabel, figname, xlabel, ylabel):\n\n plt.style.use('seaborn-paper')\n\n fig, ax = plt.subplots(figsize=(3.94*1.5, 2.76*1.5)) # (3.94, 2.76) for large and (2.5, 2) for small figure size\n for i, func in enumerate(list_func):\n func(ax, label=list_linelabel[i])\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.set_xlim((0, 120))\n ax.set_ylim((0, 1400))\n try:\n if isinstance(list_linelabel[0], str):\n ax.legend().set_visible(True)\n except KeyError:\n pass\n fig.tight_layout()\n fig.savefig(figname, dpi=300, transparent=True, bbox_inches='tight')\n\n\nif __name__ == '__main__':\n plt.style.use('seaborn-paper')\n\n # plot_examples(\n # [fire_travel], [None],\n # 'fire_travel.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n # )\n\n plot_examples(\n [fire_travel, heat_transfer_travel], [\"Gas temperature\", \"Steel temperature\"],\n 'heat_transfer_travel.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n )\n\n plot_examples(\n [fire_param], [None],\n 'fire_param.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n )\n\n plot_examples(\n [fire_param, heat_transfer_param], [\"Gas temperature\", \"Steel temperature\"],\n 'heat_transfer_param.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n )\n\n plot_examples(\n [fire_travel, fire_param], [\"Gas temperature - Parametric fire\", \"Gas temperature - Travelling fire\"],\n 'fire_travel_param.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n )\n\n plot_examples(\n [fire_iso834], [None],\n 'fire_iso.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n )\n\n # plot_examples(\n # [fire_iso834, heattran], [\"Gas temperature\", \"Steel temperature\"],\n # 'heat_transfer_param.png', 'Time [minute]', 'Temperature [$^{\\circ}C$]'\n # )\n","sub_path":"test/mc_figures.py","file_name":"mc_figures.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"636209498","text":"__all__ = [\"Discord\"]\n\nimport asyncio\nimport logging\nimport time\nfrom typing import Optional\n\nimport aiohttp\nfrom discord.ext import commands\nfrom discord import DiscordException, Intents\n\nfrom .management import Management\nfrom .utils import clean_content\n\nlog = logging.getLogger(__name__)\n\n\ndef ensure_valid_nick(nick: str) -> str:\n \"\"\"Ensure that a nickname from XMPP is valid to be used as a webhook\n username in Discord.\n \"\"\"\n if len(nick) < 2:\n return f\"<{nick}>\"\n if len(nick) > 32:\n return nick[:32]\n return nick\n\n\nclass Discord:\n \"\"\"A wrapper around a Discord client that mirrors XMPP messages to a room's\n configured webhook.\n \"\"\"\n\n def __init__(self, *, config):\n self.config = config\n intents = Intents.default()\n\n # members intent is required to resolve discord.User/discord.Member\n # on command parameters\n intents.members = True\n intents.typing = False\n\n self.client = commands.Bot(\n intents=intents, command_prefix=commands.when_mentioned\n )\n self.client.add_cog(Management(self.client, self.config))\n self.session = aiohttp.ClientSession(loop=self.client.loop)\n\n self.client.loop.create_task(self._sender())\n\n self._queue = []\n self._incoming = asyncio.Event()\n\n #: { int: (timestamp, str) }\n self._avatar_cache = {}\n\n async def _get_from_cache(self, user_id: int) -> Optional[str]:\n \"\"\"Get an avatar in cache.\"\"\"\n\n # if we insert anything into the cache, invalidation_ts\n # represents when that value will become invalidated.\n\n # it uses time.monotonic() because the monotonic clock\n # is way more stable than the general clock.\n current = time.monotonic()\n\n # the default is 30 minutes when not provided\n cache_period = self.config[\"discord\"].get(\"avatar_cache\", 80 * 60)\n\n invalidation_ts = current + cache_period\n\n value = self._avatar_cache.get(user_id)\n\n if value is None:\n # try get_user_info, which has a 1/1 ratelimit.\n # since it has that low of a ratelimit we cache\n # the resulting avatar url internally for 30 minutes.\n user = await self.client.fetch_user(user_id)\n\n # user not found, write that in cache so we don't need\n # to keep checking later on.\n if user is None:\n self._avatar_cache[user_id] = (invalidation_ts, None)\n return None\n\n # user found, store its avatar url in cache and return it\n avatar_url = user.avatar_url_as(format=\"png\")\n self._avatar_cache[user_id] = (invalidation_ts, avatar_url)\n return avatar_url\n\n user_ts, avatar_url = value\n\n # if the user cache value is invalid,\n # we recall _get_from_cache with the given user id deleted\n # so that it calls get_user_info and writes the new data\n # to cache.\n if current > user_ts:\n self._avatar_cache.pop(user_id)\n return await self._get_from_cache(user_id)\n\n return avatar_url\n\n async def resolve_avatar(self, member) -> Optional[str]:\n \"\"\"Resolve an avatar url, given a XMPP member.\n\n This caches the given avatar url for a set period of time.\n \"\"\"\n mappings = self.config[\"discord\"].get(\"jid_map\", {})\n user_id = mappings.get(str(member.direct_jid))\n\n # if nothing on the map, there isn't a need\n # to check our caches\n if user_id is None:\n return None\n\n user = self.client.get_user(user_id)\n\n # if the user is already in the client's cache,\n # we use it (it will also be better updated\n # due to USER_UPDATE events)\n if user is not None:\n return str(user.avatar_url_as(format=\"png\"))\n\n return await self._get_from_cache(user_id)\n\n async def bridge(self, room, msg, member, source):\n \"\"\"Add a MUC message to the queue to be processed.\"\"\"\n content = msg.body.any()\n\n if len(content) > 1900:\n content = content[:1900] + \"... (trimmed)\"\n\n payload = {\n \"username\": ensure_valid_nick(member.nick),\n \"content\": clean_content(content),\n \"avatar_url\": await self.resolve_avatar(member),\n }\n\n log.debug(\"adding message to queue\")\n\n # add this message to the queue\n self._queue.append(\n {\n \"webhook_url\": room.config[\"webhook\"],\n \"payload\": payload,\n }\n )\n\n self._incoming.set()\n\n async def _send_all(self):\n \"\"\"Send all pending webhook messages.\"\"\"\n log.debug(\"working on %d jobs...\", len(self._queue))\n for job in self._queue:\n try:\n resp = await self.session.post(job[\"webhook_url\"], json=job[\"payload\"])\n await asyncio.sleep(self.config[\"discord\"].get(\"delay\", 0.25))\n except Exception:\n log.exception(\"failed to bridge content\")\n\n if resp.status not in (200, 204):\n try:\n body = await resp.read()\n except Exception:\n body = \"\"\n\n log.warning(\n \"failed to bridge discord -> xmpp. status=%d, body=%r, payload=%r\",\n resp.status,\n body,\n job[\"payload\"],\n )\n\n self._queue.clear()\n self._incoming.clear()\n\n async def _sender(self):\n while True:\n log.debug(\"waiting for messages...\")\n await self._incoming.wait()\n\n log.debug(\"emptying queue\")\n await self._send_all()\n\n async def boot(self):\n log.info(\"connecting to discord...\")\n await self.client.start(self.config[\"discord\"][\"token\"])\n","sub_path":"black_hole/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"313675055","text":"\"\"\"User Images handlers\"\"\"\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport json,datetime\nimport binascii\nimport os\nfrom tornado import gen, web\nimport base64\nfrom .. import orm\nfrom ..utils import admin_only\nfrom .base import APIHandler\nfrom .users import admin_or_self, UserAPIHandler\n\nclass _ImageAPIHandler(UserAPIHandler):\n\n def _check_image_model(self, data):\n return True\n checks = [lambda x : x in data.keys() for x in ['image_name','version_tag','description','Dockerfile']]\n if all(checks):\n return True\n return False\n \n def _image_model(self, user, image):\n \"\"\"Produce the model for an docker image.\"\"\"\n return {\n 'owner': user.name,\n 'status':image.status,\n 'create_time':str(image.create_time),\n 'last_update':str(image.last_update),\n 'config':image.config\n }\n \n def find_user_images(self, user):\n images = orm.Image.find_all(self.db, user.id)\n return images\n \n def find_user_image(self, user, image_name):\n image = orm.Image.find_one(self.db, user.id, image_name)\n return image\n \nclass UserImageListAPIHandler(_ImageAPIHandler): \n \n @admin_or_self\n def get(self, name): \n user = self.find_user(name)\n if user is None:\n raise web.HTTPError(400, \"User [{}] doesn't exists.\".format(name))\n \n aa = []\n images = self.find_user_images(user)\n for image in images:\n aa.append(self._image_model(user, image))\n self.set_status(200)\n self.write(json.dumps(aa))\n \nclass UserImageAPIHandler(_ImageAPIHandler):\n \n @admin_or_self\n @gen.coroutine\n def post(self, name, image_name):\n user = self.find_user(name)\n if user is None:\n raise web.HTTPError(400, \"User [{}] doesn't exists.\".format(name))\n image = self.find_user_image(user, image_name)\n if image is not None:\n raise web.HTTPError(401, \"Image name [{}] already exists.\".format(image_name))\n \n data = self.get_json_body()\n\n if data:\n if not self._check_image_model(data):\n raise web.HTTPError(401, \"A valid image config must have name, description, docker_image, workspace_software.\")\n else :\n raise web.HTTPError(401, \"Image config is empty.\")\n \n new_image= orm.Image(name=image_name, user_id = user.id, config=json.dumps(data),status=\"pending\",\n create_time = datetime.datetime.now(), last_update = datetime.datetime.now())\n self.db.add(new_image)\n self.db.commit()\n self.set_status(200)\n \n ###build it in docker image.\n ####\n #### fix me.\n \n @admin_or_self\n def get(self, name, image_name):\n user = self.find_user(name)\n if user is None:\n raise web.HTTPError(400, \"User [{}] doesn't exists.\".format(name))\n if image_name is None or image_name == \"\":\n raise web.HTTPError(400, \"Image name cannot be null or empty.\")\n \n image = self.find_user_image(user, image_name)\n self.write(json.dumps(self._image_model(user, image)))\n\n \n @admin_or_self\n @gen.coroutine\n def delete(self, name, image_name):\n user = self.find_user(name)\n if user is None:\n raise web.HTTPError(400, \"User [{}] doesn't exists.\".format(name))\n if image_name is None or image_name == \"\":\n raise web.HTTPError(400, \"Image name cannot be null or empty.\")\n \n image = self.find_user_image(user, image_name)\n if image is None:\n raise web.HTTPError(400, \"image [{}] doesn't exist.\".format(image_name))\n ###Delete in docker image.\n ####\n #### fix me.\n \n self.log.info(\"Deleting image %s for user %s\", image_name, name)\n self.db.delete(image)\n self.db.commit()\n self.set_status(204)\n\n\ndefault_handlers = [\n (r\"/api/user/([^/]+)/images/?\", UserImageListAPIHandler),\n (r\"/api/user/([^/]+)/image/([^/]*)/?\", UserImageAPIHandler),\n]\n\n\n","sub_path":"jupyterhub/apihandlers/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"556839027","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © Spyder Project Contributors\n# Licensed under the terms of the MIT License\n# (see spyder/__init__.py for details)\n\n\"\"\"\nIn addition to the remote_call mechanism implemented in CommBase:\n - Implements _wait_reply, so blocking calls can be made.\n\"\"\"\nimport os\nimport time\nimport threading\nimport pickle\n\nfrom spyder_kernels.comms.commbase import CommBase, CommError\nfrom spyder_kernels.py3compat import TimeoutError, PY2\n\n\nclass FrontendComm(CommBase):\n \"\"\"Mixin to implement the spyder_shell_api\"\"\"\n\n def __init__(self, kernel):\n super(FrontendComm, self).__init__()\n\n # Comms\n self._pid = os.getpid()\n self.kernel = kernel\n self.kernel.comm_manager.register_target(\n self._comm_name, self._comm_open)\n\n if not PY2:\n self._main_thread_id = threading.get_ident()\n\n def remote_call(self, comm_id=None, blocking=False, callback=None):\n \"\"\"Get a handler for remote calls.\"\"\"\n return super(FrontendComm, self).remote_call(\n blocking=blocking, comm_id=comm_id, callback=callback)\n\n # --- Private --------\n def _wait_reply(self, call_id, call_name, timeout):\n \"\"\"Wait until the frontend replies to a request.\"\"\"\n if call_id in self._reply_inbox:\n return\n\n # There is no get_ident in Py2\n if not PY2 and self._main_thread_id != threading.get_ident():\n # We can't call kernel.do_one_iteration from this thread.\n # And we have no reason to think the main thread is not busy.\n raise CommError(\n \"Can't make blocking calls from non-main threads.\")\n\n t_start = time.time()\n while call_id not in self._reply_inbox:\n if time.time() > t_start + timeout:\n raise TimeoutError(\n \"Timeout while waiting for '{}' reply\".format(\n call_name))\n priority = 0\n while priority is not None:\n priority = self.kernel.do_one_iteration()\n if priority is not None:\n # For Python2\n priority = priority.result()\n\n def _comm_open(self, comm, msg):\n \"\"\"\n A new comm is open!\n \"\"\"\n self._register_comm(comm)\n self._set_pickle_protocol(msg['content']['data']['pickle_protocol'])\n self.remote_call()._set_pickle_protocol(pickle.HIGHEST_PROTOCOL)\n\n def _async_error(self, error_wrapper):\n \"\"\"\n Send an async error back to the frontend to be displayed.\n \"\"\"\n self.remote_call()._async_error(error_wrapper)\n","sub_path":"spyder_kernels/comms/frontendcomm.py","file_name":"frontendcomm.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"120503811","text":"from collections import deque, defaultdict\nimport pytest\nfrom bluesky import Msg\nfrom bluesky.examples import (det, det1, det2, Mover, NullStatus, motor,\n SynGauss, Reader)\nfrom bluesky.plans import (create, save, read, monitor, unmonitor, null,\n abs_set, rel_set, trigger, sleep, wait, checkpoint,\n clear_checkpoint, pause, deferred_pause, kickoff,\n collect, configure, stage, unstage, subscribe,\n unsubscribe, open_run, close_run, wait_for, mv,\n subs_context, run_context, event_context,\n baseline_context, monitor_context,\n stage_context, planify, finalize_wrapper,\n fly_during_wrapper, reset_positions_wrapper,\n monitor_during_wrapper,\n lazily_stage_wrapper, relative_set_wrapper,\n subs_wrapper, trigger_and_read, stop,\n repeater, caching_repeater, count, Count, Scan,\n fly_during_decorator, subs_decorator,\n monitor_during_decorator,\n inject_md_wrapper, finalize_decorator)\nfrom bluesky.spec_api import configure_count_time_wrapper\n\nfrom bluesky.utils import all_safe_rewind\n\n\nclass DummyMover:\n def __init__(self, name):\n self._value = 0\n self.name = name\n\n def describe(self):\n return {self.name: {}}\n\n def set(self, value):\n self._value = value\n return NullStatus()\n\n def read_configuration(self):\n return {}\n\n def describe_configuration(self):\n return {}\n\n def read(self):\n return {self.name: {'value': self._value, 'timestamp': 0}}\n\n\ndef cb(name, doc):\n pass\n\n\n@pytest.mark.parametrize(\n 'plan,plan_args,plan_kwargs,msgs',\n [(create, (), {}, [Msg('create', name='primary')]),\n (create, ('custom_name',), {}, [Msg('create', name='custom_name')]),\n (save, (), {}, [Msg('save')]),\n (read, (det,), {}, [Msg('read', det)]),\n (monitor, ('foo',), {}, [Msg('monitor', 'foo', name=None)]),\n (monitor, ('foo',), {'name': 'c'}, [Msg('monitor', 'foo', name='c')]),\n (unmonitor, ('foo',), {}, [Msg('unmonitor', 'foo')]),\n (null, (), {}, [Msg('null')]),\n (stop, ('foo',), {}, [Msg('stop', 'foo')]),\n (abs_set, (det, 5), {}, [Msg('set', det, 5, group=None)]),\n (abs_set, (det, 5), {'group': 'A'}, [Msg('set', det, 5, group='A')]),\n (abs_set, (det, 5), {'group': 'A', 'wait': True},\n [Msg('set', det, 5, group='A'), Msg('wait', None, group='A')]),\n (rel_set, (det, 5), {}, [Msg('read', det),\n Msg('set', det, 5, group=None)]),\n (rel_set, (det, 5), {'group': 'A'}, [Msg('read', det),\n Msg('set', det, 5, group='A')]),\n (rel_set, (det, 5), {'group': 'A', 'wait': True},\n [Msg('read', det), Msg('set', det, 5, group='A'),\n Msg('wait', None, group='A')]),\n (trigger, (det,), {}, [Msg('trigger', det, group=None)]),\n (trigger, (det,), {'group': 'A'}, [Msg('trigger', det, group='A')]),\n (sleep, (2,), {}, [Msg('sleep', None, 2)]),\n (wait, (), {}, [Msg('wait', None, group=None)]),\n (wait, ('A',), {}, [Msg('wait', None, group='A')]),\n (checkpoint, (), {}, [Msg('checkpoint')]),\n (clear_checkpoint, (), {}, [Msg('clear_checkpoint')]),\n (pause, (), {}, [Msg('pause', None, defer=False)]),\n (deferred_pause, (), {}, [Msg('pause', None, defer=True)]),\n (kickoff, ('foo',), {}, [Msg('kickoff', 'foo', group=None)]),\n (kickoff, ('foo',), {'custom': 5}, [Msg('kickoff', 'foo',\n group=None, custom=5)]),\n (collect, ('foo',), {}, [Msg('collect', 'foo', stream=False)]),\n (configure, (det, 1), {'a': 2}, [Msg('configure', det, 1, a=2)]),\n (stage, (det,), {}, [Msg('stage', det)]),\n (unstage, (det,), {}, [Msg('unstage', det)]),\n (subscribe, ('all', 'func_placeholder'), {}, [Msg('subscribe', None, 'all',\n 'func_placeholder')]),\n (unsubscribe, (1,), {}, [Msg('unsubscribe', None, token=1)]),\n (open_run, (), {}, [Msg('open_run')]),\n (open_run, (), {'md': {'a': 1}}, [Msg('open_run', a=1)]),\n (close_run, (), {}, [Msg('close_run')]),\n (wait_for, (['fut1', 'fut2'],), {}, [Msg('wait_for', None, ['fut1', 'fut2'])]),\n ])\ndef test_stub_plans(plan, plan_args, plan_kwargs, msgs):\n assert list(plan(*plan_args, **plan_kwargs)) == msgs\n\n\ndef test_mv():\n # special-case mv because the group is not configurable\n actual = list(mv(det1, 1, det2, 2))\n expected = [Msg('set', det1, 1, group=None),\n Msg('set', det2, 2, group=None),\n Msg('wait', None, group=None)]\n strip_group(actual)\n strip_group(expected)\n assert actual == expected\n\n\n@pytest.mark.parametrize(\n 'cm,args,kwargs,before,after',\n [(baseline_context, ([det1, det2],), {},\n [Msg('trigger', det1),\n Msg('trigger', det2),\n Msg('wait'),\n Msg('create', None, name='baseline'),\n Msg('read', det1),\n Msg('read', det2),\n Msg('save')],\n [Msg('trigger', det1),\n Msg('trigger', det2),\n Msg('wait'),\n Msg('create', None, name='baseline'),\n Msg('read', det1),\n Msg('read', det2),\n Msg('save')]),\n (stage_context, ([det1, det2],), {},\n [Msg('stage', det1),\n Msg('stage', det2)],\n [Msg('unstage', det2),\n Msg('unstage', det1)]),\n (subs_context, ({'all': [cb]},), {},\n [Msg('subscribe', None, 'all', cb)],\n [Msg('unsubscribe', None, token=None)]),\n (monitor_context, (['sig'],), {},\n list(monitor('sig')),\n list(unmonitor('sig'))),\n (event_context, (), {},\n [Msg('create', name='primary')],\n [Msg('save')]),\n (run_context, (), {'md': {'a': 1}},\n [Msg('open_run', a=1)],\n [Msg('close_run')]),\n ])\ndef test_plan_contexts(cm, args, kwargs, before, after):\n @planify\n def plan():\n ps = deque()\n with cm(ps, *args, **kwargs):\n ps.append(['sentinel'])\n return ps\n\n actual_before = []\n actual_after = []\n target = actual_before\n for msg in plan():\n if msg == 'sentinel':\n target = actual_after\n continue\n msg.kwargs.pop('group', None)\n target.append(msg)\n assert actual_before == before\n assert actual_after == after\n\n\ndef strip_group(plan):\n for msg in plan:\n msg.kwargs.pop('group', None)\n\n\ndef test_monitor_during_wrapper():\n def plan():\n # can't use 2 * [Msg('open_run'), Msg('null'), Msg('close_run')]\n # because plan_mutator sees the same ids twice and skips them\n yield from [Msg('open_run'), Msg('null'), Msg('close_run'),\n Msg('open_run'), Msg('null'), Msg('close_run')]\n\n processed_plan = list(monitor_during_wrapper(plan(), [det]))\n expected = 2 * [Msg('open_run'),\n # inserted\n Msg('monitor', det, name=(det.name + '_monitor')),\n Msg('null'),\n Msg('unmonitor', det), # inserted\n Msg('close_run')]\n\n strip_group(processed_plan)\n assert processed_plan == expected\n\n processed_plan = list(monitor_during_decorator([det])(plan)())\n strip_group(processed_plan)\n assert processed_plan == expected\n\n\ndef test_descriptor_layout_from_monitor(fresh_RE):\n collector = []\n det = Reader('det', {k: lambda: i for i, k in enumerate('abcd')},\n read_attrs=list('ab'), conf_attrs=list('cd'))\n\n def collect(name, doc):\n if name == 'descriptor':\n collector.append(doc)\n\n fresh_RE([Msg('open_run'),\n Msg('monitor', det, name=det.name),\n Msg('unmonitor', det),\n Msg('close_run')], collect)\n\n descriptor, = collector\n assert descriptor['object_keys'] == {det.name: list(det.describe().keys())}\n assert descriptor['data_keys'] == det.describe()\n conf = descriptor['configuration'][det.name]\n assert conf['data_keys'] == det.describe_configuration()\n vals = {key: val['value'] for key, val in det.read_configuration().items()}\n timestamps = {key: val['timestamp']\n for key, val in det.read_configuration().items()}\n assert conf['data'] == vals\n assert conf['timestamps'].keys() == timestamps.keys()\n for val in conf['timestamps'].values():\n assert type(val) is float # can't check actual value; time has passed\n\n\ndef test_fly_during():\n def plan():\n # can't use 2 * [Msg('open_run'), Msg('null'), Msg('close_run')]\n # because plan_mutator sees the same ids twice and skips them\n yield from [Msg('open_run'), Msg('null'), Msg('close_run'),\n Msg('open_run'), Msg('null'), Msg('close_run')]\n\n processed_plan = list(fly_during_wrapper(plan(), ['foo']))\n expected = 2 * [Msg('open_run'),\n Msg('kickoff', 'foo'), Msg('wait'), # inserted\n Msg('null'),\n Msg('complete', 'foo'), Msg('wait'), # inserted\n Msg('collect', 'foo'), # inserted\n Msg('close_run')]\n\n strip_group(processed_plan)\n assert processed_plan == expected\n\n processed_plan = list(fly_during_decorator(['foo'])(plan)())\n strip_group(processed_plan)\n assert processed_plan == expected\n\n\ndef test_lazily_stage():\n def plan():\n yield from [Msg('read', det1), Msg('read', det1), Msg('read', det2)]\n\n processed_plan = list(lazily_stage_wrapper(plan()))\n\n expected = [Msg('stage', det1), Msg('read', det1), Msg('read', det1),\n Msg('stage', det2), Msg('read', det2), Msg('unstage', det2),\n Msg('unstage', det1)]\n\n assert processed_plan == expected\n\n\ndef test_subs():\n\n def cb(name, doc):\n pass\n\n def plan(*args, **kwargs):\n # check that args to plan are passed through\n yield from [Msg('null', None, *args, **kwargs)]\n\n processed_plan = list(subs_wrapper(plan('test_arg', test_kwarg='val'),\n {'all': cb}))\n\n expected = [Msg('subscribe', None, 'all', cb),\n Msg('null', None, 'test_arg', test_kwarg='val'),\n Msg('unsubscribe', token=None)]\n\n assert processed_plan == expected\n\n processed_plan = list(subs_decorator({'all': cb})(plan)('test_arg',\n test_kwarg='val'))\n assert processed_plan == expected\n\n\ndef test_md():\n def plan():\n yield from open_run(md={'a': 1})\n\n processed_plan = list(inject_md_wrapper(plan(), {'b': 2}))\n\n expected = [Msg('open_run', None, a=1, b=2)]\n\n assert processed_plan == expected\n\n\ndef test_finalize():\n def plan():\n yield from [Msg('null')]\n\n def cleanup_plan():\n yield from [Msg('read', det)]\n\n # wrapper accepts list\n processed_plan = list(finalize_wrapper(plan(), [Msg('read', det)]))\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # or func that returns list\n def plan():\n yield from [Msg('null')]\n\n processed_plan = list(finalize_wrapper(plan(), lambda: [Msg('read', det)]))\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # or generator instance\n def plan():\n yield from [Msg('null')]\n\n processed_plan = list(finalize_wrapper(plan(), cleanup_plan()))\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # or generator func\n def plan():\n yield from [Msg('null')]\n\n processed_plan = list(finalize_wrapper(plan(), cleanup_plan))\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # decorator accepts generator func\n processed_plan = list(finalize_decorator(cleanup_plan)(plan)())\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # or func that returns list\n processed_plan = list(finalize_decorator(lambda: [Msg('read', det)])(plan)())\n expected = [Msg('null'), Msg('read', det)]\n assert processed_plan == expected\n\n # decorator does NOT accept list\n with pytest.raises(TypeError):\n list(finalize_decorator([Msg('read', det)])(plan)())\n\n # nor generator instance\n with pytest.raises(TypeError):\n list(finalize_decorator(cleanup_plan())(plan)())\n\n\ndef test_finalize_runs_after_error(fresh_RE):\n def plan():\n yield from [Msg('null')]\n raise Exception\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n try:\n fresh_RE(finalize_wrapper(plan(), [Msg('read', det)]))\n except Exception:\n pass # swallow the Exception; we are interested in msgs below\n\n expected = [Msg('null'), Msg('read', det)]\n\n assert msgs == expected\n\n\ndef test_reset_positions(fresh_RE):\n motor = Mover('a', {'a': lambda x: x}, {'x': 0})\n motor.set(5)\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n\n def plan():\n yield from (m for m in [Msg('set', motor, 8)])\n\n fresh_RE(reset_positions_wrapper(plan()))\n\n expected = [Msg('set', motor, 8), Msg('set', motor, 5), Msg('wait')]\n\n for msg in msgs:\n msg.kwargs.pop('group', None)\n\n assert msgs == expected\n\n\ndef test_reset_positions_no_position_attr(fresh_RE):\n motor = DummyMover('motor')\n motor.set(5)\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n\n def plan():\n yield from (m for m in [Msg('set', motor, 8)])\n\n fresh_RE(reset_positions_wrapper(plan()))\n\n expected = [Msg('read', motor),\n Msg('set', motor, 8), Msg('set', motor, 5), Msg('wait')]\n\n for msg in msgs:\n msg.kwargs.pop('group', None)\n\n assert msgs == expected\n\n\ndef test_relative_set(fresh_RE):\n motor = Mover('a', {'a': lambda x: x}, {'x': 0})\n motor.set(5)\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n\n def plan():\n yield from (m for m in [Msg('set', motor, 8)])\n\n fresh_RE(relative_set_wrapper(plan()))\n\n expected = [Msg('set', motor, 13)]\n\n for msg in msgs:\n msg.kwargs.pop('group', None)\n\n assert msgs == expected\n\n\ndef test_relative_set_no_position_attr(fresh_RE):\n motor = DummyMover('motor')\n motor.set(5)\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n\n def plan():\n yield from (m for m in [Msg('set', motor, 8)])\n\n fresh_RE(relative_set_wrapper(plan()))\n\n expected = [Msg('read', motor),\n Msg('set', motor, 13)]\n\n for msg in msgs:\n msg.kwargs.pop('group', None)\n\n assert msgs == expected\n\n\ndef test_configure_count_time(fresh_RE):\n class DummySignal:\n def put(self, val):\n pass\n\n def get(self):\n return 3\n\n def set(self, val):\n return NullStatus()\n\n det = DummyMover('det')\n det.count_time = DummySignal()\n\n def plan():\n yield from (m for m in [Msg('read', det)])\n\n msgs = []\n\n def accumulator(msg):\n msgs.append(msg)\n\n fresh_RE.msg_hook = accumulator\n\n fresh_RE(configure_count_time_wrapper(plan(), 7))\n\n expected = [Msg('set', det.count_time, 7), Msg('wait'),\n Msg('read', det), Msg('set', det.count_time, 3),\n Msg('wait')]\n\n for msg in msgs:\n msg.kwargs.pop('group', None)\n\n assert msgs == expected\n\n\ndef test_repeater():\n def plan(*args):\n yield from args\n\n actual = list(repeater(3, plan, 1, 2, 3))\n assert actual == 3 * [1, 2, 3]\n\n p = repeater(None, plan, 1, 2, 3)\n assert next(p) == 1\n assert next(p) == 2\n assert next(p) == 3\n assert next(p) == 1\n\n\ndef test_caching_repeater():\n def plan(*args):\n yield from args\n\n plan_instance = plan(1, 2, 3)\n actual = list(caching_repeater(3, plan_instance))\n assert actual == 3 * [1, 2, 3]\n\n plan_instance = plan(1, 2, 3)\n p = caching_repeater(None, plan_instance)\n assert next(p) == 1\n assert next(p) == 2\n assert next(p) == 3\n assert next(p) == 1\n\n\ndef test_trigger_and_read():\n msgs = list(trigger_and_read([det]))\n expected = [Msg('trigger', det), Msg('wait'),\n Msg('create', name='primary'), Msg('read', det), Msg('save')]\n for msg in msgs:\n msg.kwargs.pop('group', None)\n assert msgs == expected\n\n msgs = list(trigger_and_read([det], 'custom'))\n expected = [Msg('trigger', det), Msg('wait'), Msg('create', name='custom'),\n Msg('read', det), Msg('save')]\n for msg in msgs:\n msg.kwargs.pop('group', None)\n assert msgs == expected\n\n\ndef test_count_delay_argument():\n # num=7 but delay only provides 5 entries\n with pytest.raises(ValueError):\n # count raises ValueError when delay generator is expired\n list(count([det], num=7, delay=(2**i for i in range(5))))\n\n # num=6 with 5 delays between should product 6 readings\n msgs = count([det], num=6, delay=(2**i for i in range(5)))\n read_count = len([msg for msg in msgs if msg.command == 'read'])\n assert read_count == 6\n\n # num=5 with 5 delays should produce 5 readings\n msgs = count([det], num=5, delay=(2**i for i in range(5)))\n read_count = len([msg for msg in msgs if msg.command == 'read'])\n assert read_count == 5\n\n # num=4 with 5 delays should produce 4 readings\n msgs = count([det], num=4, delay=(2**i for i in range(5)))\n read_count = len([msg for msg in msgs if msg.command == 'read'])\n assert read_count == 4\n\n # num=None with 5 delays should produce 6 readings\n msgs = count([det], num=None, delay=(2**i for i in range(5)))\n read_count = len([msg for msg in msgs if msg.command == 'read'])\n assert read_count == 6\n\n\ndef test_plan_md(fresh_RE):\n mutable = []\n md = {'color': 'red'}\n\n def collector(name, doc):\n mutable.append(doc)\n\n # test genereator\n mutable.clear()\n fresh_RE(count([det], md=md), collector)\n assert 'color' in mutable[0]\n\n # test Plan with explicit __init__\n mutable.clear()\n fresh_RE(Count([det], md=md), collector)\n assert 'color' in mutable[0]\n\n # test Plan with implicit __init__ (created via metaclasss)\n mutable.clear()\n fresh_RE(Scan([det], motor, 1, 2, 2, md=md), collector)\n assert 'color' in mutable[0]\n\n\ndef test_infinite_count(fresh_RE):\n loop = fresh_RE.loop\n\n loop.call_later(2, fresh_RE.stop)\n docs = defaultdict(list)\n\n def collector(name, doc):\n docs[name].append(doc)\n\n fresh_RE(count([det], num=None), collector)\n\n assert len(docs['start']) == 1\n assert len(docs['stop']) == 1\n assert len(docs['descriptor']) == 1\n assert len(docs['event']) > 0\n\n\ndef test_no_rewind_device():\n class FakeSig:\n def get(self):\n return False\n\n det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1)\n det.rewindable = FakeSig()\n\n assert not all_safe_rewind([det])\n\n\ndef test_monitor(fresh_RE):\n RE = fresh_RE\n RE(monitor_during_wrapper(count([det], 5), [det1]))\n","sub_path":"bluesky/tests/test_new_examples.py","file_name":"test_new_examples.py","file_ext":"py","file_size_in_byte":19388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"209070252","text":"import numpy as np\nimport cv2\ndef gray2rgb(img):\n if len(img.shape)!=2:\n return False\n h, w = img.shape\n size=(h,w)\n shape=(*size,3)\n\n result=np.zeros(shape,np.uint8)\n result[:,:,0]=img #0是b通道\n result[:,:,1]=img #0是g通道\n result[:,:,2]=img #0是r\n return result\n\n\ndef show_img(img):\n cv2.imshow(\"new image\", img)\n cv2.waitKey()\n\ndef write_text(text,img):\n font = cv2.FONT_HERSHEY_SIMPLEX\n color = (0, 0, 255) # BGR 格式颜色\n thickness = 2\n font_scale = 1\n text_size, _ = cv2.getTextSize(text, font, font_scale, thickness)\n text_x = int((img.shape[1] - text_size[0]) / 2)\n text_y = int((img.shape[0] + text_size[1]) / 2)\n out=cv2.putText(img, text, (text_x, text_y), font, font_scale, color, thickness)\n return out\n\ndef parse_part(n1,n2,y,image,image_size):\n th=np.where((y>=n1) & (y<=n2),0,255)\n th=th.astype('uint8')\n contours, hierarchy = cv2.findContours(th,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n for contour in contours:\n img = cv2.drawContours(img, contour, -1, (255, 255, 255), 1)\n points=len(np.where(th ==0)[0])\n precent=points/image_size\n print(points,precent)\n th=gray2rgb(th)\n th=write_text(text=str(precent),img=th)\n\ndef fenxi(filepath):\n img=cv2.imread(filepath)\n h,w,depth=img.shape\n image_size=h*w\n print(image_size)\n img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n y, u, v = cv2.split(img_yuv)\n\n [[0,50],[50,100],[100,150],[150,200],[200,230],[230,255]]\n\n th1=np.where((y>=0) & (y<=50),0,255)\n th1=th1.astype('uint8')\n contours, hierarchy = cv2.findContours(th1, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n for contour in contours:\n img = cv2.drawContours(img, contour, -1, (255, 255, 255), 1)\n points1=len(np.where(th1 ==0)[0])\n precent1=points1/image_size\n print(points1,precent1)\n th1=gray2rgb(th1)\n th1=write_text(text=str(precent1),img=th1)\n\n\n th2=np.where((y>50) & (y<=100),0,255)\n th2=th2.astype('uint8')\n contours, hierarchy = cv2.findContours(th2, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n for contour in contours:\n img = cv2.drawContours(img, contour, -1, (0, 0, 255), 1)\n points2 = len(np.where(th2 == 0)[0])\n precent2 = points2 / image_size\n print(points2,precent2)\n th2=gray2rgb(th2)\n th2=write_text(text=str(precent2),img=th2)\n\n\n th3=np.where((y>100) & (y<=150),0,255)\n th3=th3.astype('uint8')\n contours, hierarchy = cv2.findContours(th3, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n # for contour in contours:\n # img = cv2.drawContours(img, contour, -1, (0, 0, 255), 1)\n points3 = len(np.where(th3 == 0)[0])\n precent3 = points3 / image_size\n print(points3,precent3)\n th3=gray2rgb(th3)\n th3=write_text(text=str(precent3),img=th3)\n\n th4=np.where((y>150) & (y<=200),0,255)\n th4=th4.astype('uint8')\n contours, hierarchy = cv2.findContours(th4, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n # for contour in contours:\n # img = cv2.drawContours(img, contour, -1, (0, 0, 255), 1)\n points4 = len(np.where(th4 == 0)[0])\n precent4 = points4 / image_size\n print(points4,precent4)\n th4=gray2rgb(th4)\n th4=write_text(text=str(precent4),img=th4)\n\n th5 = np.where((y > 200) & (y <=230), 0, 255)\n th5 = th5.astype('uint8')\n contours, hierarchy = cv2.findContours(th5, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n # for contour in contours:\n # img = cv2.drawContours(img, contour, -1, (0, 0, 255), 1)\n points5 = len(np.where(th5 == 0)[0])\n precent5 = points5 / image_size\n print(points5, precent5)\n th5 = gray2rgb(th5)\n th5 = write_text(text=str(precent5), img=th5)\n \n th6 = np.where((y > 230) & (y <=255), 0, 255)\n th6 = th6.astype('uint8')\n contours, hierarchy = cv2.findContours(th6, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n # for contour in contours:\n # img = cv2.drawContours(img, contour, -1, (0, 0, 266), 1)\n points6 = len(np.where(th6 == 0)[0])\n precent6 = points6 / image_size\n print(points6, precent6)\n th6 = gray2rgb(th6)\n th6 = write_text(text=str(precent6), img=th6)\n\n out=np.concatenate((img, th1,th2,th3,th4,th5,th6))\n print(precent1+precent2+precent3+precent4+precent5+precent6)\n show_img(out)\n\n cv2.imwrite('aaa.png', out)\n\nfenxi(filepath='simple.jpg')\n\n","sub_path":"job/西瓜-分离通道,统计颜色/颜色统计-第1版.py","file_name":"颜色统计-第1版.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"80622757","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 29 13:50:53 2019\n\n@author: ckielasjensen\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport scipy.optimize as sop\nfrom tensorflow.keras.models import load_model\nimport time\n\nimport bezier as bez\nfrom optimization import BezOptimization\n\n\nSAFE_DIST = 1\nMODEL = 'rmsprop_mean_squared_error_3epochs_500_0.model'\n\ndef generate_random_state(xmin, xmax, ymin, ymax, numPts):\n \"\"\"\n \"\"\"\n# pts = [(ub-lb)*np.random.random(2)+lb]\n pts = [np.array(((xmax-xmin)*np.random.random()+xmin,\n (ymax-ymin)*np.random.random()+ymin))]\n while len(pts) < numPts:\n newPt = np.array(((xmax-xmin)*np.random.random()+xmin,\n (ymax-ymin)*np.random.random()+ymin))\n distances = [np.linalg.norm(newPt-pt) for pt in pts]\n if min(distances) > SAFE_DIST:\n pts.append(newPt)\n\n return pts\n\n\nif __name__ == '__main__':\n\n numVeh = 5\n dim = 2\n deg = 5\n \n model = load_model(MODEL)\n\n temp = generate_random_state(-10, 10, -10, 10, numVeh*2 + 2)\n initPoints = temp[:numVeh]\n finalPoints = temp[numVeh:-2]\n pointObstacles = temp[-2:]\n\n # Kind of confusing but what it does is unwrap the list of tuples into\n # just a list\n input_state = [j for i in initPoints for j in i]\n input_state += [j for i in finalPoints for j in i]\n input_state += [j for i in pointObstacles for j in i]\n\n bezopt = BezOptimization(numVeh=numVeh,\n dimension=dim,\n degree=deg,\n minimizeGoal='Euclidean',\n maxSep=SAFE_DIST,\n# maxSpeed=5,\n# maxAngRate=1,\n initPoints=initPoints,\n finalPoints=finalPoints,\n# initSpeeds=[1]*numVeh,\n# finalSpeeds=[1]*numVeh,\n# initAngs=[np.pi/2]*numVeh,\n# finalAngs=[np.pi/2]*numVeh,\n pointObstacles=pointObstacles\n )\n\n \n \n\n ineqCons = [{'type': 'ineq', 'fun': bezopt.temporalSeparationConstraints}]\n\n print('starting')\n startTime = time.time()\n xGuess_straightLine = bezopt.generateGuess(std=0)\n results = sop.minimize(\n bezopt.objectiveFunction,\n x0=xGuess_straightLine,\n method='SLSQP',\n constraints=ineqCons,\n options={'maxiter': 250,\n 'disp': True,\n 'iprint': 1}\n )\n endTime = time.time()\n\n\n print('---')\n print('Straight Line Computation Time: {}'.format(endTime - startTime))\n print('---')\n\n cptsSL = bezopt.reshapeVector(results.x)\n\n print('starting')\n startTime = time.time()\n xGuess_DNN = model.predict(np.atleast_2d(input_state))\n results = sop.minimize(\n bezopt.objectiveFunction,\n x0=xGuess_DNN,\n method='SLSQP',\n constraints=ineqCons,\n options={'maxiter': 250,\n 'disp': True,\n 'iprint': 1}\n )\n endTime = time.time()\n\n print('---')\n print('DNN Computation Time: {}'.format(endTime - startTime))\n print('---')\n\n cptsDNN = bezopt.reshapeVector(results.x)\n\n ###########################################################################\n # Plot Results\n ###########################################################################\n plt.close('all')\n numVeh = bezopt.model['numVeh']\n dim = bezopt.model['dim']\n maxSep = bezopt.model['maxSep']\n\n ###### Straight Line Results\n fig, ax = plt.subplots()\n curves = []\n for i in range(numVeh):\n curves.append(bez.Bezier(cptsSL[i*dim:(i+1)*dim]))\n for curve in curves:\n plt.plot(curve.curve[0], curve.curve[1], '-',\n curve.cpts[0], curve.cpts[1], '.--')\n\n obstacle1 = plt.Circle(bezopt.pointObstacles[0],\n radius=maxSep,\n edgecolor='Black',\n facecolor='red')\n obstacle2 = plt.Circle(bezopt.pointObstacles[1],\n radius=maxSep,\n edgecolor='Black',\n facecolor='green')\n ax.add_artist(obstacle1)\n ax.add_artist(obstacle2)\n plt.xlim([-10, 10])\n plt.ylim([-10, 10])\n plt.title('Straight Line Guess Result', fontsize=28)\n plt.xlabel('X Position', fontsize=20)\n plt.ylabel('Y Position', fontsize=20)\n\n ####### KNN Results\n fig, ax = plt.subplots()\n curves = []\n for i in range(numVeh):\n curves.append(bez.Bezier(cptsDNN[i*dim:(i+1)*dim]))\n for curve in curves:\n plt.plot(curve.curve[0], curve.curve[1], '-',\n curve.cpts[0], curve.cpts[1], '.--')\n\n obstacle1 = plt.Circle(bezopt.pointObstacles[0],\n radius=maxSep,\n edgecolor='Black',\n facecolor='red')\n obstacle2 = plt.Circle(bezopt.pointObstacles[1],\n radius=maxSep,\n edgecolor='Black',\n facecolor='green')\n ax.add_artist(obstacle1)\n ax.add_artist(obstacle2)\n plt.xlim([-10, 10])\n plt.ylim([-10, 10])\n plt.title('DNN Guess Result', fontsize=28)\n plt.xlabel('X Position', fontsize=20)\n plt.ylabel('Y Position', fontsize=20)\n\n ###### DNN Initial Guess\n fig, ax = plt.subplots()\n cpts = bezopt.reshapeVector(xGuess_DNN)\n curves = []\n for i in range(numVeh):\n curves.append(bez.Bezier(cpts[i*dim:(i+1)*dim]))\n for curve in curves:\n plt.plot(curve.curve[0], curve.curve[1], '-',\n curve.cpts[0], curve.cpts[1], '.--')\n\n obstacle1 = plt.Circle(bezopt.pointObstacles[0],\n radius=maxSep,\n edgecolor='Black',\n facecolor='red')\n obstacle2 = plt.Circle(bezopt.pointObstacles[1],\n radius=maxSep,\n edgecolor='Black',\n facecolor='green')\n ax.add_artist(obstacle1)\n ax.add_artist(obstacle2)\n plt.xlim([-10, 10])\n plt.ylim([-10, 10])\n plt.title('DNN Initial Guess', fontsize=28)\n plt.xlabel('X Position', fontsize=20)\n plt.ylabel('Y Position', fontsize=20)\n\n plt.show()\n","sub_path":"DNNTesting.py","file_name":"DNNTesting.py","file_ext":"py","file_size_in_byte":6618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"404392374","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\nimport json\nimport os\nimport sys\n\ndef pretty_json(json_path, insert='pretty'):\n with open(json_path, 'r') as f:\n j = json.load(f)\n json_split_path = os.path.splitext(json_path)\n new_json_path = json_split_path[0] + '_'+ insert + json_split_path[1]\n with open(new_json_path, 'w') as f:\n json.dump(j, f, indent=2, ensure_ascii=False)\n\nif __name__ == '__main__':\n p = sys.argv[1]\n pretty_json(p)\n","sub_path":"cv/freeanchorsquare/data/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"530854225","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport pandas as pd\nimport math\nimport numpy as np\nfrom ringloss.loss_func import RingLoss\nfrom PIL import Image\nimport types\nfrom torch.utils.tensorboard import SummaryWriter\n\nALIGNED_PATH = \"WC-MS-Celeb/WC-MS-Celeb.tsv\"\nCROPPED_PATH = \"WC-MS-Celeb/WC-MS-Celeb.tsv\"\n\nJSON_PATH = \"WC-MS-Celeb/json/\"\nCLASSES_PATH = \"WC-MS-Celeb/data/WDList\"\nNUM_CLASSES = 77543\nNUM_IMAGES = 5429085\n\nBATCH_SIZE = 16\nNUM_WORKERS = 4\n\nLEARNING_RATE = 0.0005\nWEIGHT_DECAY = 0.0\nMOMENTUM = 0.8\nLR_STEP = 10\n\nMODE = \"pretrained\"\nOPTIM = \"adam\"\n\ndef get_num_classes():\n s = set()\n with open(ALIGNED_PATH) as a:\n for line in a:\n s.add(line.split('\\t')[0])\n return len(s)\n\ndef get_shapes():\n with open(ALIGNED_PATH) as a:\n for line in a:\n out = io.BytesIO(base64.b64decode(line.split('\\t')[-1]))\n img = Image.open(out)\n print(img)\n input()\n\ndef classes():\n lst = []\n idx = {}\n with open(CLASSES_PATH) as classes:\n for line in classes:\n lst.append(line.rstrip())\n idx[lst[-1]] = len(lst) - 1\n return lst, idx\n\n\nclass AlignedWC(torch.utils.data.Dataset):\n def __init__(self, tsv, transform = None):\n super(AlignedWC).__init__() \n self.df = pd.read_csv(tsv, names=['tag', 'image'], sep='\\t')\n self.classes, self.class_idx = classes()\n self.tf = transform\n\n def transform(self, image):\n if self.tf == None:\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize([224,224]),\n torchvision.transforms.ToTensor()\n ])\n else:\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize([224,224]),\n self.tf,\n torchvision.transforms.ToTensor()\n ])\n return transform(image)\n \n\n def loader(self, image):\n return torchvision.datasets.folder.default_loader('aligned/'+image)\n\n def __getitem__(self, index):\n return (\n self.class_idx[self.df.iloc[index]['tag']],\n self.transform(self.loader(self.df.iloc[index]['image']))\n )\n\n def __len__(self):\n return len(self.df.index)\n\ndef train(trainloader, num_epochs = 10):\n # partially from pytorch docs\n for epoch in range(num_epochs):\n run_loss = 0.0\n run_ring = 0.0\n for i, data in enumerate(trainloader, 0):\n optimizer.zero_grad()\n inputs, labels = data[1].to(device), data[0].to(device) \n outputs = model(inputs)\n softmax_val = loss(softmax(outputs),labels)\n ring_val = ringloss(outputs)\n loss_val = softmax_val + ring_val\n loss_val.backward()\n optimizer.step() \n \n run_loss += softmax_val.item()\n run_ring += ring_val.item()\n if i % 50 == 49: # print every 10 mini-batches\n correct = (outputs.data.max(1)[1] == labels).sum().item()\n '''\n print('[%d, %5d, %.3f%%] acc: %d/%d, speed: %.6fs, loss: %.3f' %\n (\n epoch + 1,\n BATCH_SIZE*(i + 1),\n 100*BATCH_SIZE*(i+1)/(NUM_IMAGES*0.8), \n correct, \n BATCH_SIZE, \n (time.time()-start)/(BATCH_SIZE*50), \n run_loss / 50\n )\n )\n '''\n writer.add_scalar('Loss/train', (run_loss+run_ring)/50, BATCH_SIZE*(i+1))\n writer.add_scalar('Softmax/train', run_loss/50, BATCH_SIZE*(i+1))\n writer.add_scalar('Ring/train', run_ring/50, BATCH_SIZE*(i+1))\n writer.add_scalar('Accuracy/train', correct/(BATCH_SIZE), BATCH_SIZE*(i+1))\n run_loss = 0.0\n run_ring = 0.0\n scheduler.step()\n\ndef test(testloader):\n # partially from pytorch docs\n correct = 0\n total = 0\n with torch.no_grad():\n for data in testloader:\n images, labels = data[1], data[0]\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted==labels).sum().item()\n print(\"correct {}/{}\".format(correct, total))\n\nwriter = SummaryWriter()\n\ndata = AlignedWC(ALIGNED_PATH)\n\ntrain_data, test_data = torch.utils.data.random_split(data, [int(.8*len(data)), int(.2*len(data))])\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size = BATCH_SIZE, num_workers = NUM_WORKERS, pin_memory=True, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size = BATCH_SIZE, num_workers = NUM_WORKERS, pin_memory=True, shuffle=True)\n\nif MODE == \"pretrained\":\n model = torchvision.models.resnet50(pretrained=True)\n model.fc = nn.Linear(2048, NUM_CLASSES)\nelif MODE == \"default\":\n model = torchvision.models.resnet50(pretrained=False, num_classes=NUM_CLASSES)\n\nsoftmax = nn.LogSoftmax(dim=1)\nloss = nn.NLLLoss()\nringloss = RingLoss(type='auto', loss_weight=1.0)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nmodel.to(device)\nsoftmax.to(device)\nloss.to(device)\nringloss.to(device)\n\nif OPTIM == \"adam\":\n optimizer = torch.optim.AdamW(params=model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)\nelif OPTIM == \"sgd\":\n optimizer = torch.optim.SGD(params=model.parameters(), lr=LEARNING_RATE, momentum=MOMENTUM)\n \nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=LR_STEP, gamma=0.1)\n \ntrain(train_loader, num_epochs=1)\ntest(test_loader)\ntorch.save(model.state_dict(), \"epoch1.pth\")\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"571464336","text":"#!/usr/bin/python3\n# computer_ping.py a simple ping to see if a box is up or not.\n\n# load needed modules\nimport logging\nimport os\nimport time\nimport subprocess\nimport sys\n\n# check for command line arguments, ask for target if none provided.\nif len(sys.argv) > 1:\n host_name = (sys.argv[1])\nelse:\n host_name = input(\"What host are you looking for? (Enter hostname or ip address): \")\n\n\ndef ping_computer(ping_this):\n \"\"\"Function to call Linux ping command.\"\"\"\n response = os.system('ping -c 1 -W 100 ' + ping_this + ' > /dev/null 2>&1')\n return response\n\n\ndef alert_box(ping_result):\n \"\"\"Function to open text file with the result of the final ping (up or down).\"\"\"\n file_object = open(host_name + '_ping_result.txt', 'w')\n file_object.write(host_name + ping_result)\n file_object.close()\n subprocess.Popen(['xdg-open', host_name + '_ping_result.txt'])\n # subprocess.Popen(['/usr/bin/mousepad', hostName + '_ping_result.txt'])\n\n\n# try pinging the host over the course of an hour, stops when the target is up.\nattempts_left = 6\nattempt_number = 1\n\nwhile attempts_left > 0:\n upDown = ping_computer(host_name)\n if upDown == 0:\n logging.info('Attempt ' + str(attempt_number) + ': ' + host_name + ' is up!')\n alert_box(' is up at this time!')\n break\n elif attempts_left == 1:\n logging.info('Attempt ' + str(attempt_number) + ': ' + host_name + ' is down! Ping attempts ended')\n alert_box(' is down at this time! Tried for 1 hour.')\n else:\n logging.info('Attempt ' + str(attempt_number) + ': ' + host_name + ' is down, trying again in 10 minutes.')\n time.sleep(600)\n attempt_number += 1\n attempts_left -= 1\n# sleep 3 seconds to allow system to open text file, before deleting text file. \ntime.sleep(3)\nos.remove(host_name + '_ping_result.txt')\n","sub_path":"computer_ping/lComputerPing.py","file_name":"lComputerPing.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"337897158","text":"import library.config as config\nimport library.data_parsers.location_extractor as location_extractor\nimport library.data_parsers.simple_dt_extract as simple_dt_extract\nimport library.data_parsers.simple_timer_extract as simple_timer_extract\nimport library.jarvis_api.Dictionary as diction\nimport library.jarvis_api.Help as he\nimport library.jarvis_api.Joke as joker\nimport library.jarvis_api.Lists as listf\nimport library.jarvis_api.Reminders as remind\nimport library.jarvis_api.alarm as alarm\nimport library.jarvis_api.display_news as display_news\nimport library.jarvis_api.display_time as display_time\nimport library.jarvis_api.face_identify as face_id\nimport library.jarvis_api.lock as lock\nimport library.jarvis_api.logoff as logoff\nimport library.jarvis_api.music_player as music_player\nimport library.jarvis_api.restart as restart\nimport library.jarvis_api.searchup as search\nimport library.jarvis_api.shutdown as shutdown\nimport library.jarvis_api.start_program as start_program\nimport library.jarvis_api.start as start\nimport library.jarvis_api.timer as timer\nimport library.jarvis_api.wea as wea\nimport library.jarvis_api.wolfram_alpha as wolfram_alpha\nimport library.speech_text_processors.text_to_speech as text_to_speech\n\nconfig.main()\n\n\ndef main(context, text):\n try:\n intent = context.query_result.intent.display_name\n action = context.query_result.action\n if intent == 'weather':\n city = context.query_result.parameters.fields[\"geo-city\"].string_value\n state = context.query_result.parameters.fields[\"geo-state-us\"].string_value\n country = context.query_result.parameters.fields[\"geo-country\"].string_value\n days = simple_dt_extract.diff_days(text)\n response = wea.get_weather(city, state, country, days)\n return response\n elif intent == 'startProgram':\n start.main()\n return None\n elif intent == 'musicPlaying':\n music_player.main()\n return None\n elif intent == 'time':\n location = location_extractor.main(text)\n response = display_time.main(location)\n return response\n elif intent == 'setAlarm':\n alarm_time = simple_dt_extract.alarm_extract(text)\n response = alarm.set_alarm(alarm_time)\n return response\n elif intent == 'tellAlarms':\n response = alarm.tell_alarms()\n return response\n elif intent == \"setReminder\":\n time = simple_dt_extract.alarm_extract(text)\n name = config.username\n reminder = context.query_result.parameters.fields['desc'].string_value\n response = remind.remindset(name, reminder, time)\n return response\n elif intent == 'Joke':\n response = joker.joke()\n return response\n elif intent == \"Dictionary\":\n x = context.query_result.parameters.fields['dict'].string_value\n response = diction.dict(x)\n return None\n elif intent == 'logoffCom':\n logoff.main()\n return None\n elif intent == 'lockCom':\n lock.main()\n return None\n elif intent == 'news':\n topic = context.query_result.parameters.fields['topic'].string_value\n location = context.query_result.parameters.fields['location'].string_value\n response = display_news.main(topic, location)\n return response\n elif intent == 'shutdownCom':\n shutdown.main()\n return None\n elif intent == 'restartCom':\n restart.main()\n return None\n elif intent == \"setList\":\n item = context.query_result.parameters.fields['item'].list_value.values[0].string_value\n listname = context.query_result.parameters.fields['list'].list_value.values[0].string_value\n user = config.username\n response = listf.setList(user, item, listname)\n return response\n elif intent == \"getList\":\n listname = context.query_result.parameters.fields['list'].string_value\n user = config.username\n response = listf.getList(user, listname)\n return response\n elif intent == \"delList\":\n listname = context.query_result.parameters.fields['list'].list_value.values[0].string_value\n user = config.username\n response = listf.delList(user, listname)\n return response\n elif intent == \"delItem\":\n listname = context.query_result.parameters.fields['list'].list_value.values[0].string_value\n user = config.username\n item = context.query_result.parameters.fields['item'].list_value.values[0].string_value\n response = listf.delItem(user, listname, item)\n return response\n\n elif intent == \"help\":\n response = he.wcid()\n return None\n elif intent == 'setTimer':\n seconds = simple_timer_extract.main(text)\n timer.set_timer(seconds)\n return 'Set timer successfully'\n elif intent == 'search':\n query = context.query_result.parameters.fields['q'].string_value\n if len(query) > 0:\n response = search.main(query)\n return response\n else:\n return \"Your search is invalid\"\n elif intent == 'ddlc':\n return \"I believe Yuri is best girl, but there are different opinions\"\n elif intent == 'face_id':\n response=face_id.main()\n return response\n elif intent == 'run_program':\n response=start_program.main()\n return ''\n else:\n success_bool = wolfram_alpha.main(text)\n if success_bool:\n pass\n elif not success_bool:\n return context.query_result.fulfillment_text\n elif 'smalltalk' in action:\n return context.query_result.fulfillment_text\n else:\n return \"Sorry, I don't understand your command, would you like to google that?\"\n except SyntaxError:#Exception as e:\n print ('[Jarvis]')\n print (' Sorry I have hit an error : ' + str(e))\n text_to_speech.main('Sorry I have hit an error')\n option = input('\\n[>]Do you want to continue running Jarvis? [y/n] : ')\n if option == 'y':\n print ('\\n')\n return\n else:\n raise KeyboardInterrupt\n","sub_path":"desktop_jarvis/library/api_responder.py","file_name":"api_responder.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"377174286","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2018 Hailong Gao \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\n\"\"\"\n\nimport unittest\nfrom app import create_app, db\n\n\nclass APITestCase(unittest.TestCase):\n def setUp(self):\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n self.client = self.app.test_client()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def get_api_headers(self):\n return {\n 'Accept': 'application/json'\n }\n\n def test_404(self):\n resp = self.client.get('/wrong/url', headers=self.get_api_headers())\n self.assertEqual(resp.status_code, 404)\n # json_resp = json.loads(resp.get_data(as_text=True))\n # self.assertEqual(json_resp['error'], 'not found')\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"21976575","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # Create memories\n url(r'^post-timeline-memory/$', views.new_timeline_post, name='new_timeline_post'),\n url(r'^post-memory/$', views.new_post, name='new_post'),\n\n # View memories\n url(r'^$', views.memories, name='memories'),\n url(r'^(?P[0-9]+)/$', views.memory_detail, name='memory_detail'),\n\n # View pictures\n url(r'^bilder/$', views.pictures, name='pictures'),\n url(r'^bilder/(?P[0-9]+)/$', views.picture_detail, name='picture_detail'),\n\n # Timeline\n url(r'^minneslinje/$', views.timeline, name='timeline')\n]\n","sub_path":"memories/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"185356725","text":"import math\n\n\n\"\"\"\n=======================================\nSurface Brightness Models\n=======================================\n\"\"\"\n\n\ndef sersic_intensity(r, params):\n \"\"\"\n A single-Sersic intensity profile. (Sersic, (1968))\n :param r: The radius being examined\n :param params: Parameters specified by the input galaxy.\n :return: \n \"\"\"\n hlr, I_e, n = params[\"hlr\"], params[\"I_e\"], params[\"n\"]\n b_n = get_b(n)\n try:\n exponential = -b_n * (((r / hlr) ** (1 / n)) - 1)\n return I_e * math.exp(exponential)\n except:\n print(\"Input Error: Check your parameters.\")\n return None\n\n\ndef sersic_sb(r, params):\n \"\"\"\n A Sersic surface brightness profile. (Sersic(1968), Graham(2005)) \n :param r: \n :param params: \n :return: \n \"\"\"\n sb_eff, n, hlr = params[\"sb_eff\"], params[\"n\"], params[\"hlr\"]\n\n try:\n piece_1 = 2.5 * get_b(n) / math.log(10)\n piece_2 = ((r / hlr) ** (1 / n)) - 1\n return (sb_eff + piece_1 * piece_2)\n except:\n print(\"Input Error: Check your parameters.\")\n return None\n\n\ndef nuker(r, params):\n \"\"\"\n A galaxy profile defined by the Nuker Law (Erwin et al. (2003)).\n This profile is used as a means to probe details about a galaxy's core. It does not accurately plot a galaxy's\n light profile past the Half Light Radius\n :param r: The radius being examined\n :param params: Parameters for a galaxy\n :return: \n \"\"\"\n r_b, I_b, ipls, opls, alpha = params[\"r_b\"], params[\"I_b\"], params[\"ipls\"], params[\"opls\"], params[\"alpha\"]\n if r == 0:\n return params[\"I_0\"]\n try:\n p_1 = (opls - ipls) / alpha\n p_2 = (ipls - opls) / alpha\n f_1 = (r / r_b) ** (-ipls)\n f_2 = (1 + ((r / r_b) ** alpha))\n return I_b * (2 ** p_1) * f_1 * (f_2 ** p_2)\n except:\n print(\"Input Error: Check your parameters.\")\n return None\n\n\ndef core_sersic(r, params):\n \"\"\"\n A combined Nuker-law, Sersic model for intensity.\n :param r: The radius being examined\n :param params Parameters specified by the input galaxy\n :return: \n \"\"\"\n if r == 0:\n return params[\"I_0\"]\n r_b, I_b, ipls, alpha = params[\"r_b\"], params[\"I_b\"], params[\"ipls\"], params[\"alpha\"]\n hlr, n = params[\"hlr\"], params[\"n\"]\n\n b_n = get_b(n)\n I_prime = I_b * (2 ** (-ipls / alpha)) * math.exp(b_n * (2 ** (1 / (alpha * n))) * ((r_b / hlr) ** (1 / n)))\n f_1 = 1 + (((r_b / r) ** alpha) ** (ipls / alpha))\n f_2 = math.exp(-b_n * ((r ** alpha + r_b ** alpha) / (hlr ** alpha)) ** (1/(n * alpha)))\n\n return I_prime * f_1 * f_2\n\n\ndef get_b(n):\n if n < 8:\n return (1.9992 * n) - 0.3271\n else:\n return (2 * n) - (1 / 3)\n","sub_path":"uchu/models/SBModel.py","file_name":"SBModel.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"309398019","text":"\"\"\"\ntime : o(n)\nspace : o(n)\n\"\"\"\nclass Solution(object):\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n \n seen = set()\n res = set()\n for i in range(len(s) - 10 +1): #checking for every string of length 10 if it is repeated by maintaining a seen hashset\n if s[i:i + 10] in seen:\n res.add(s[i:i + 10])\n \n seen.add(s[i:i + 10])\n \n return res","sub_path":"Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"119281793","text":"# Copyright 2018 Kyoto University (Hirofumi Inaguma)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\"\"\"Custom Sampler.\"\"\"\n\nimport numpy as np\nimport random\n\nfrom torch.utils.data.sampler import BatchSampler\n\nfrom neural_sp.datasets.utils import discourse_bucketing\nfrom neural_sp.datasets.utils import longform_bucketing\nfrom neural_sp.datasets.utils import set_batch_size\nfrom neural_sp.datasets.utils import shuffle_bucketing\n\n\nclass CustomBatchSampler(BatchSampler):\n\n def __init__(self, df, batch_size, dynamic_batching,\n shuffle_bucket, discourse_aware, sort_stop_epoch,\n longform_max_n_frames=0, seed=1):\n \"\"\"Custom BatchSampler.\n\n Args:\n\n df (pandas.DataFrame): dataframe for the main task\n batch_size (int): size of mini-batch\n dynamic_batching (bool): change batch size dynamically in training\n shuffle_bucket (bool): gather similar length of utterances and shuffle them\n discourse_aware (bool): sort in the discourse order\n sort_stop_epoch (int): After sort_stop_epoch, training will revert\n back to a random order\n longform_max_n_frames (int): maximum input length for long-form evaluation\n\n \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n\n self.df = df\n self.batch_size = batch_size\n self.batch_size_tmp = None\n\n self.dynamic_batching = dynamic_batching\n self.shuffle_bucket = shuffle_bucket\n self.sort_stop_epoch = sort_stop_epoch\n self.discourse_aware = discourse_aware\n self.longform_xmax = longform_max_n_frames\n\n self._offset = 0\n # NOTE: epoch should not be counted in BatchSampler\n\n if discourse_aware:\n self.indices_buckets = discourse_bucketing(df, batch_size)\n self._iteration = len(self.indices_buckets)\n elif longform_max_n_frames > 0:\n self.indices_buckets = longform_bucketing(df, batch_size, longform_max_n_frames)\n self._iteration = len(self.indices_buckets)\n elif shuffle_bucket:\n self.indices_buckets = shuffle_bucketing(df, batch_size, self.dynamic_batching, seed)\n self._iteration = len(self.indices_buckets)\n else:\n self.indices = list(df.index)\n # calculate #iteration in advance\n self.calculate_iteration()\n\n def __len__(self):\n \"\"\"Number of mini-batches.\"\"\"\n return self._iteration\n\n def __iter__(self):\n while True:\n indices, is_new_epoch = self.sample_index()\n if is_new_epoch:\n self.reset()\n yield indices\n if is_new_epoch:\n break\n\n @property\n def offset(self):\n return self._offset\n\n def calculate_iteration(self):\n self._iteration = 0\n is_new_epoch = False\n while not is_new_epoch:\n _, is_new_epoch = self.sample_index()\n self._iteration += 1\n random.seed(1) # reset seed\n self.reset()\n\n def reset(self, batch_size=None, epoch=None):\n \"\"\"Reset data counter and offset.\n\n Args:\n batch_size (int): size of mini-batch\n epoch (int): current epoch\n\n \"\"\"\n if batch_size is None:\n batch_size = self.batch_size\n\n self._offset = 0\n\n if self.discourse_aware:\n self.indices_buckets = discourse_bucketing(self.df, batch_size)\n elif self.longform_xmax > 0:\n self.indices_buckets = longform_bucketing(self.df, batch_size, self.longform_xmax)\n elif self.shuffle_bucket:\n self.indices_buckets = shuffle_bucketing(self.df, batch_size, self.dynamic_batching, seed=epoch)\n else:\n self.indices = list(self.df.index)\n self.batch_size_tmp = batch_size\n\n def sample_index(self):\n \"\"\"Sample data indices of mini-batch.\n\n Returns:\n indices (np.ndarray): indices of dataframe in the current mini-batch\n\n \"\"\"\n if self.discourse_aware or self.longform_xmax > 0 or self.shuffle_bucket:\n indices = self.indices_buckets.pop(0)\n self._offset += len(indices)\n is_new_epoch = (len(self.indices_buckets) == 0)\n\n if self.shuffle_bucket:\n # Shuffle utterances in mini-batch\n indices = random.sample(indices, len(indices))\n else:\n if self.batch_size_tmp is not None:\n batch_size = self.batch_size_tmp\n else:\n batch_size = self.batch_size\n\n # Change batch size dynamically\n min_xlen = self.df[self._offset:self._offset + 1]['xlen'].values[0]\n min_ylen = self.df[self._offset:self._offset + 1]['ylen'].values[0]\n batch_size = set_batch_size(batch_size, min_xlen, min_ylen, self.dynamic_batching)\n is_new_epoch = (len(self.indices) <= batch_size)\n\n if is_new_epoch:\n # Last mini-batch\n indices = self.indices[:]\n self._offset = len(self.df)\n else:\n indices = list(self.df[self._offset:self._offset + batch_size].index)\n self._offset += len(indices)\n\n # Shuffle utterances in mini-batch\n indices = random.sample(indices, len(indices))\n\n for i in indices:\n self.indices.remove(i)\n\n return indices, is_new_epoch\n","sub_path":"neural_sp/datasets/asr/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"648566962","text":"import cv2\nimport numpy as np\n\ndef process_frame(diff, frame1):\n # convert image to grayscale\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n\n # apply gaussian blur to image to remove noise\n blur = cv2.GaussianBlur(gray, (3, 3), 0)\n\n # apply threshold to image to convert to binary image\n _, threshold = cv2.threshold(blur, 22, 255, cv2.THRESH_BINARY)\n\n # dialate threshold image to bring out edges more\n dialate = cv2.dilate(threshold, None, iterations=3)\n\n # find contours from dialated image\n contours, hierachy = cv2.findContours(dialate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n # loop through all contours to find bounding box rectangle coordinates\n for contour in contours:\n (x, y, w, h) = cv2.boundingRect(contour)\n\n # calculate area of contour, to eliminate smaller contours\n if cv2.contourArea(contour) < 10000:\n continue\n\n # draw rectangle on image\n frame1 = cv2.rectangle(frame1, (x, y), (x+w, y+h), (21, 123, 98), 3)\n return frame1\n\n# create video capture object\n# cap = cv2.VideoCapture('static.mp4')\ncap = cv2.VideoCapture(0)\n\n# get the first two frames\nret, frame1 = cap.read()\nret, frame2 = cap.read()\n\n\nwhile cap.isOpened():\n # get the difference between current and previous frame\n diff = cv2.absdiff(frame1, frame2)\n\n # pass difference to process frame function for further processing\n result = process_frame(diff, frame1)\n\n # show processed result \n cv2.imshow('Recorded Feed', result)\n\n frame1 = frame2\n\n _, frame2 = cap.read()\n\n if cv2.waitKey(40) == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"motion_detect_trial.py","file_name":"motion_detect_trial.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"44077522","text":"# coding: utf-8\n\nfrom datetime import datetime\nfrom flask import Blueprint, render_template, redirect, url_for\nfrom apps.event.models import Event\n\n\nmod = Blueprint(\n 'event',\n __name__,\n url_prefix='/event',\n template_folder='templates'\n)\n\n@mod.route('/')\ndef index():\n current_date = datetime.today()\n future_events = Event.query(Event.start_date>=current_date).filter(Event.is_public==True).order(Event.start_date)\n past_events = Event.query(Event.start_date/')\ndef event(event_id):\n event = Event.get_by_id(event_id)\n if not event or not event.is_public:\n return redirect(url_for('event.index'))\n return render_template(\n 'event/event.html',\n html_class='event',\n event=event\n )","sub_path":"apps/event/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"558266464","text":"#coding= utf-8\nimport requests\n\nclass Tiebaspider:\n def __init__(self,tieba_name):\n self.tieba_name = tieba_name\n self.url_temp = \"http://tieba.baidu.com/f?kw=\"+ tieba_name +\"&ie=utf-8&pn={}\"\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36\"}\n def get_url_list(self):\n url_list = []\n for i in range (1000):\n url_list.append(self.url_temp.format(i*50))\n return url_list\n def parse_url(self,url):\n response = requests.get(url,headers = self.headers )\n return response.content.decode()\n\n def save_html(self,html,num):\n file_path = \"{}-帝{}也.html\".format(self.tieba_name,num)\n with open(file_path,\"w\",encoding=\"utf-8\") as f:\n f.write(html)\n\n def run(self):\n url_list = self.get_url_list()\n for url in url_list:\n html = self.parse_url(url)\n num = url_list.index(url) + 1\n self.save_html(html,num)\n\n\n\nif __name__ == \"__main__\":\n tieba_spider = Tiebaspider(\"李毅\")\n tieba_spider.run()","sub_path":"awesome-python3-webapp/baidu_spider.py","file_name":"baidu_spider.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"88730949","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n left = 0\n right = len(nums) - 1\n index = -1\n while left <= right:\n mid = (left + right) / 2\n if target == nums[mid]:\n index = mid\n break\n\n elif target > nums[mid]:\n left = mid + 1\n\n else:\n right = mid - 1\n if index == -1:\n return [-1, -1]\n\n start = end = 0\n find_s = False\n find_e = False\n while not find_s or not find_e:\n if index - start >= 0 and nums[index - start] == target:\n start += 1\n else:\n find_s = True\n\n if index + end <= len(nums) - 1 and nums[index + end] == target:\n end += 1\n else:\n find_e = True\n\n return [index - start + 1, index + end - 1]\n","sub_path":"Week05/34.py","file_name":"34.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"413260914","text":"import os\nimport datetime\nimport pandas as pd\nimport requests\nimport io\nimport sqlalchemy\n\nfrom cs50 import SQL\nfrom flask import Flask, flash, redirect, render_template, request, session\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\nfrom bs4 import BeautifulSoup\nfrom functions import apology\n\n# Configure application\napp = Flask(__name__)\n\n# Ensure templates are auto-reloaded\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n\n# Ensure responses aren't cached\n@app.after_request\ndef after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n# Configure session to use filesystem (instead of signed cookies)\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Configure CS50 Library to use SQLite database for tracking COVID-19 cases on all campuses\nengine = sqlalchemy.create_engine(\"sqlite:///unicases.db\")\ndata = requests.get(\"https://raw.githubusercontent.com/nytimes/covid-19-data/master/colleges/colleges.csv\").content\ndf = pd.read_csv(io.StringIO(data.decode('utf-8')))\ndf.to_sql('unicases', con=engine, schema=None, if_exists=\"replace\", index=None,\n dtype={'date': sqlalchemy.types.Text(), 'state': sqlalchemy.types.Text(), \"county\": sqlalchemy.types.Text(),\n \"city\": sqlalchemy.types.Text(), \"ipeds_id\": sqlalchemy.types.Integer(), \"college\": sqlalchemy.types.Text(),\n \"cases\": sqlalchemy.types.Integer(), \"notes\": sqlalchemy.types.Text()}) # Column types required specification\ndb = SQL(\"sqlite:///unicases.db\")\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Show site homepage\"\"\"\n\n # Render the homepage file\n return render_template(\"c19index.html\")\n\n\n# Extract positivity rate from Harvard dashboard\nharvard = requests.get(\"https://www.harvard.edu/coronavirus/harvard-university-wide-covid-19-testing-dashboard#note\")\nsoup = BeautifulSoup(harvard.text,'html.parser')\n\nlinks = soup.find_all('a')\nfor link in links:\n link.decompose()\n\nsuperscript = soup.find_all('sup')\nfor script in superscript:\n script.decompose()\n\nharvard_rates = soup.find_all('h1')\npositivity = harvard_rates[4]\npositivity_element = positivity.contents\n# Convert positivity rate from a list of strings to a float value for calculations\npositivity_str = ''.join(map(str, positivity_element))\npositivity_str = positivity_str[:-1] # Needed to remove the '%' symbol\nharv_positivity_rate = float(positivity_str)\n\ndef errorhandler(e):\n \"\"\"Handle error\"\"\"\n if not isinstance(e, HTTPException):\n e = InternalServerError()\n return apology(e.name, e.code)\n\n\n# Listen for errors\nfor code in default_exceptions:\n app.errorhandler(code)(errorhandler)","sub_path":".~c9_invoke_35R5w4.py","file_name":".~c9_invoke_35R5w4.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"468643339","text":"import os\nimport matplotlib.pyplot as plt\nfrom train import EPOCH\n\ndef read_loss(directory:str, epoch:int):\n avg_losses = []\n for i in range(epoch):\n try:\n with open(os.path.join(directory, str(i) + \"_avg\"), 'r') as fp:\n data = fp.readline()\n avg_losses += [float(data[8:13])]\n except FileNotFoundError:\n print(\"File not found\")\n return avg_losses, i\n return avg_losses, epoch\n\nx = range(EPOCH)\ny, _ = read_loss(\"visual-loss\", EPOCH)\n\nplt.plot(x, y)\n\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.title(\"Loss Graph\")\n\nplt.legend()\nfig = plt.gcf()\nfig.savefig('visual_loss.png')\n\n","sub_path":"history/02/normal-train/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"532008466","text":"import sys\nimport random\n\nans1 = True\n\nwhile ans1:\n que = input(\"Ask the magic 8 ball a question(1-8) press .(dot) if you want to exit : \")\n print(\"\\n\")\n\n anss = random.randint(1, 8)\n\n if que == \".\":\n sys.exit()\n\n elif anss == 1:\n print(\"It is certain\")\n\n elif anss == 2:\n print(\"Outlook good\")\n\n elif anss == 3:\n print(\"You may rely on it\")\n\n elif anss == 4:\n print(\"Ask again later\")\n\n elif anss == 5:\n print(\"Concentrate and ask again\")\n\n elif anss == 6:\n print(\"Reply hazy, try again\")\n\n elif anss == 7:\n print(\"My reply is no\")\n\n elif anss == 8:\n print(\"My sources say no\")","sub_path":"Magic 8 Ball Game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"24470793","text":"import numpy as np\nimport cv2 as cv\n\nimg = cv.imread('rocks0.jpg', 1)\n#img = cv.blur(input, (3, 3))\n\nprint(img.shape)\nnimg = np.zeros((img.shape[0], img.shape[1], 3))\nT = 20\na = 7\nb = 7\nh, w, d = img.shape\nfor i in range(h):\n for j in range(w):\n avg = np.mean(img[max(0, i-a):min(h, i+a), max(0, j-b):min(w, j+b)])\n temp = img[max(0, i-a):min(h, i+a), max(0, j-b):min(w, j+b)].copy()\n temp = temp.reshape(temp.shape[0]*temp.shape[1]*temp.shape[2])\n mx = np.mean(temp[np.argsort(temp)[-5:]])\n #print(mx)\n navg = avg-(mx-avg)\n nimg[i,j] = navg + 2*(img[i,j]-avg)\n #exit(0)\nnimg = nimg.astype(np.uint8)\ncv.imshow('Frame', nimg)\ncv.imwrite('t0.jpg', nimg)\ncv.waitKey(0)\n","sub_path":"Python/contrast.py","file_name":"contrast.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"233690418","text":"\"\"\"\nCopyright (c) College of Mechatronics and Control Engineering, Shenzhen University.\nAll rights reserved.\n\nDescription :\ndqn algorithm used for controling the steer to make a vehicle keep lane.\n\nAuthor:Team Li\n\"\"\"\nimport tensorflow as tf\nimport cv2, math, sys, random, threading\n\nfrom keep_lane.basic_net.dqn_utils import action_value_net\nimport RL.rl_utils as rl_tools\n\ntry:\n sys.path.append('F:\\my_project\\driving-desicion-in-carla\\dist/carla-0.9.4-py3.7-win-amd64.egg')\n import carla\nexcept:\n raise ImportError('Please check your carla file')\nfrom carla_utils.world_ops import *\nfrom carla_utils.sensor_ops import *\n\ntf.app.flags.DEFINE_string(\n 'checkpoint_dir', '../checkpoint/keep_lane_world/corner_init',\n 'The path to a checkpoint from which to fine-tune.')\n\n\ntf.app.flags.DEFINE_integer(\n 'n_egopilots', 1, 'the number of egopilots')\n\ntf.app.flags.DEFINE_integer(\n 'img_height', 416,\n 'raw image height captured from carla')\n\ntf.app.flags.DEFINE_integer(\n 'img_width', 626,\n 'raw image width captured from carla')\n\ntf.app.flags.DEFINE_integer(\n 'net_img_height', 224,\n 'image height of network input')\n\ntf.app.flags.DEFINE_integer(\n 'net_img_width', 224,\n 'raw image width of network input')\n\ntf.app.flags.DEFINE_integer(\n 'n_action', 21,\n 'total discrete action in steer')\n\n\nFLAGS = tf.app.flags.FLAGS\n\n## carla config ##\nsemantic_camera_config = {'data_type': 'sensor.camera.semantic_segmentation', 'image_size_x': FLAGS.img_width,\n 'image_size_y': FLAGS.img_height, 'fov': 110, 'sensor_tick': 0.02,\n 'transform': carla.Transform(carla.Location(x=0.5, z=1.6)),\n 'attach_to':None}\nbgr_camera_config = {'data_type': 'sensor.camera.rgb', 'image_size_x': FLAGS.img_width,\n 'image_size_y': FLAGS.img_height, 'fov': 110, 'sensor_tick': 0.02,\n 'transform': carla.Transform(carla.Location(x=0.5, z=1.6)),\n 'attach_to':None}\nspector_camera_config = {'data_type': 'sensor.camera.rgb', 'image_size_x': FLAGS.img_width,\n 'image_size_y': FLAGS.img_height, 'fov': 110, 'sensor_tick': 0.02,\n 'transform': carla.Transform(carla.Location(x=-6, z=3.5)),\n 'attach_to':None}\ncollision_sensor_config = {'data_type': 'sensor.other.collision','attach_to': None}\ninvasion_sensor_config = {'data_type': 'sensor.other.lane_detector', 'attach_to': None}\nobstacle_sensor_config = {'data_type': 'sensor.other.obstacle', 'sensor_tick': 0.02,\n 'distance': 3, 'attach_to': None}\n\n\ndef action_index_2_steer(action_index):\n \"\"\" change the action index to steer val\n Args:\n action_index: an int between [0, n_action-1]\n Return:\n a steer val in [-1, 1]\n \"\"\"\n steer = action_index * 2 / float(FLAGS.n_action - 1) - 1. ## range is [-1, 1]\n return steer\n\n\ndef single_execuate(target, args):\n \"\"\" single thread execuate\n Args:\n target: a func\n args: args in target\n \"\"\"\n threading.Thread(target=target, args=args).start()\n\n\ndef check_whether_respawn_actors(world, vehicles):\n \"\"\"check whether to respawn the static acotors in a frequency\"\"\"\n while True:\n if carla_actors_static(vehicles, bigger_than=0.75):\n # respawn_actor_at(world, vehicles[0], spawn_points[45])\n respawn_static_actors(world, vehicles)\n time.sleep(5)\n\n\ndef online_thread(sess):\n \"\"\"a thread for target nets in DDPG\"\"\"\n while True:\n ## get current state\n imgs = []\n for camera_sensor, spector in zip(cameras, spectors):\n img = camera_sensor.get()\n img = img[int(FLAGS.img_height*1.8//5):, :, :] ## corp the ROI\n\n img = cv2.resize(img, dsize=(FLAGS.net_img_height, FLAGS.net_img_width))\n sp_img = spector.get()\n cv2.imshow('visualization', sp_img)\n imgs.append(img)\n\n current_img_state = np.array(imgs)\n current_img_state = current_img_state*2./255. - 1.\n\n ## get current action and control the egopilots\n current_action = sess.run([max_action_index_online], feed_dict={online_img_state: current_img_state})\n\n ## control the egopilots ##\n i = 0\n for egopilot, c_a in zip(egopilots, current_action):\n ## e-greedy\n current_action[i] = c_a[0]\n\n steer = action_index_2_steer(c_a[0])\n throttle = 0.5\n brake = 0.\n\n ego_v = egopilot.get_velocity()\n ego_v = math.sqrt(ego_v.x ** 2 + ego_v.y ** 2 + ego_v.z ** 2)\n if ego_v > 8. and throttle > 0.5:\n throttle = 0.5 ## avoid velocity too big\n\n ## apply control\n egopilot.apply_control(carla.VehicleControl(throttle=throttle, steer=steer, brake=brake))\n i += 1\n\n cv2.waitKey(25)\n # time.sleep(0.5) ## sleep for a while, let the action control the egopilots to next state\n\n\nif __name__ == '__main__':\n online_img_state = tf.placeholder(shape=[None, FLAGS.net_img_height, FLAGS.net_img_width, 3], dtype=tf.float32)\n\n\n act_val_net_online = action_value_net()\n act_val_online, vars_online = act_val_net_online.build_graph(img_state=online_img_state, n_action=FLAGS.n_action, is_training=False,\n var_scope='online_act_val')\n\n #########################################\n ## the best action ops in current step ##\n #########################################\n max_action_index_online = tf.argmax(act_val_online, axis=-1)\n\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=5)\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n logger.info('Tensorflow graph bulid success...')\n logger.info('Total trainable parameters:%s' %\n str(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])))\n ########################### TENSORFLOW GRAPH ######################################\n\n #### carla world init ####\n client = carla.Client('127.0.0.1', 2000)\n client.set_timeout(10.0) # seconds\n logger.info('Carla connect success...')\n\n logger.info('Carla world initing...')\n world = client.get_world()\n destroy_all_actors(world)\n\n ## spawn vehicles in carla world\n spawn_points = list(world.get_map().get_spawn_points())\n spawn_egopilot_at(world, spawn_points[45])\n # spawn_vehicles(world, n_autopilots=0, n_egopilots=FLAGS.n_egopilots)\n time.sleep(2) ## sometimes unstale\n\n autopilots = get_all_autopilots(world)\n egopilots = get_all_egopilots(world)\n\n cameras = []\n spectors = []\n lane_invasions = []\n obj_collisions = []\n # obstacle_aheads = []\n logger.info('Adding some sensors to egopilots...')\n for egopilot in egopilots:\n ## attach a camera to egopilot ##\n # semantic_camera_config['attach_to'] = egopilot\n # semantic_sensor = semantic_camera(world, semantic_camera_config)\n # cameras.append(semantic_sensor)\n\n bgr_camera_config['attach_to'] = egopilot\n bgr_sensor = bgr_camera(world, bgr_camera_config)\n cameras.append(bgr_sensor)\n\n spector_camera_config['attach_to'] = egopilot\n bgr_sensor = bgr_camera(world, spector_camera_config)\n spectors.append(bgr_sensor)\n\n ## attach collision sensor to egopilot ##\n collision_sensor_config['attach_to'] = egopilot\n collision_sensor = collision_query(world, collision_sensor_config)\n obj_collisions.append(collision_sensor)\n\n ## attach line invasion sensor to egopilot ##\n invasion_sensor_config['attach_to'] = egopilot\n lane_invasion_sensor = lane_invasion_query(world, invasion_sensor_config)\n lane_invasions.append(lane_invasion_sensor)\n\n # ## attach obstacle sensor to egopilot\n # obstacle_sensor_config['attach_to'] = egopilot\n # obstacle_sensor = obstacle_ahead_query(world, obstacle_sensor_config)\n # obstacle_aheads.append(obstacle_sensor)\n logger.info('Adding some sensors to egopilots success')\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n if ckpt:\n logger.info('loading %s...' % str(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n logger.info('Load checkpoint success...')\n else:\n raise ValueError('you must provide ture checkpoint...')\n\n check_t = threading.Thread(target=check_whether_respawn_actors, args=(world, autopilots + egopilots,))\n target_t = threading.Thread(target=online_thread, args=(sess,))\n\n target_t.daemon = True\n check_t.daemon = True\n\n check_t.start()\n # # respwan_v_t.start()\n target_t.start()\n\n # vis_memory_thread()\n while True:\n pass","sub_path":"efficient_driving/dqn_test.py","file_name":"dqn_test.py","file_ext":"py","file_size_in_byte":8943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"565092491","text":"# https://www.codechef.com/JUNE20B/problems/XYSTR\n\n\ndef solve():\n for _ in range(int(input())):\n s = input()\n\n count = index = 0\n while index < len(s) - 1:\n if s[index] != s[index + 1]:\n count += 1\n index += 2\n else:\n index += 1\n\n print(count)\n\n\nsolve()\n","sub_path":"src/arrays/chef-and-string.py","file_name":"chef-and-string.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"40768195","text":"a=999\nb=999\n\nres=0\nresA=0\nresB=0\n\nwhile a>99:\n while b>99:\n if \"\".join(reversed(str(a*b))) == str(a*b) and res-fix.py","file_name":"2b9ac8fb08d94e7735177323dc8efde335e50adb-<_convert_frame_to_apple_string>-fix.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"360896421","text":"import discord\nfrom discord.ext import commands\n\nclass on_ready_event(commands.Cog):\n def __init__(self, client: commands.Bot):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(\"\"\"\n _ _\n (.)_(.)\n _ ( _ ) _\n / \\/`-----'\\/ \\ - Meow, he said\n __\\ ( ( ) ) /__ enthusiastically.\n ) /\\ \\._./ /\\ (\n )_/ /|\\ /|\\ \\_(\n \"\"\")\n print(f\"\"\"\nStarted successfully!\nCurrently on {sum(1 for _ in self.client.guilds)} servers.\nCurrently serving {sum(1 for _ in self.client.get_all_members())} humans. \n \"\"\")\n\ndef setup(client: commands.Bot):\n client.add_cog(on_ready_event(client))","sub_path":"pytty/events/on_ready.py","file_name":"on_ready.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"348459668","text":"#coding: utf-8\n\n#Sorteie 10 inteiros entre 1 e 100 para uma lista e descubra o maior e o menor valor, sem usar as funcoes max e min\nimport os\nimport sys\n\nfrom random import randint\n\nlista = []\ni = 1\nmenor = float('inf')\nmaior = 0\n\nwhile i <= 10:\n\tn = randint(1,100)\n\tlista.append(n)\n\tif n > maior:\n\t\tmaior = n\n\tif n < menor:\n\t\tmenor = n \n\ti+=1\n\nprint('A lista é: ', lista, ' o maior número é: ', maior, ' e o menor número é: ', menor)","sub_path":"Lista4/exercicio1.py","file_name":"exercicio1.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"104030298","text":"import argparse\nimport json\nimport os.path\nimport warnings\n\nimport torch\n\nfrom .data.data_loader import SpectrogramParser\nfrom .decoder import GreedyDecoder\nfrom .opts import add_decoder_args, add_inference_args\nfrom .utils import load_model\n\nwarnings.simplefilter(\"ignore\")\n\n\ndef decode_results(decoded_output, decoded_offsets):\n results = {\n \"output\": [],\n \"_meta\": {\n \"acoustic_model\": {\"name\": os.path.basename(args.model_path)},\n \"language_model\": {\n \"name\": os.path.basename(args.lm_path)\n if args.lm_path\n else None,\n },\n \"decoder\": {\n \"lm\": args.lm_path is not None,\n \"alpha\": args.alpha if args.lm_path is not None else None,\n \"beta\": args.beta if args.lm_path is not None else None,\n \"type\": args.decoder,\n },\n },\n }\n\n for b in range(len(decoded_output)):\n for pi in range(min(args.top_paths, len(decoded_output[b]))):\n result = {\"transcription\": decoded_output[b][pi]}\n if args.offsets:\n result[\"offsets\"] = decoded_offsets[b][pi].tolist()\n results[\"output\"].append(result)\n return results\n\n\ndef transcribe(audio_path, spect_parser, model, decoder, device, use_half):\n spect = spect_parser.parse_audio(audio_path).contiguous()\n spect = spect.view(1, 1, spect.size(0), spect.size(1))\n spect = spect.to(device)\n if use_half:\n spect = spect.half()\n input_sizes = torch.IntTensor([spect.size(3)]).int()\n out, output_sizes = model(spect, input_sizes)\n decoded_output, decoded_offsets = decoder.decode(out, output_sizes)\n return decoded_output, decoded_offsets\n\n\ndef main() -> None:\n arg_parser = argparse.ArgumentParser(\n description=\"DeepSpeech transcription\"\n )\n arg_parser = add_inference_args(arg_parser)\n arg_parser.add_argument(\n \"--audio-path\", default=\"audio.wav\", help=\"Audio file to predict on\"\n )\n arg_parser.add_argument(\n \"--offsets\",\n dest=\"offsets\",\n action=\"store_true\",\n help=\"Returns time offset information\",\n )\n arg_parser = add_decoder_args(arg_parser)\n args = arg_parser.parse_args()\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n model = load_model(device, args.model_path, args.half)\n\n if args.decoder == \"beam\":\n from .decoder import BeamCTCDecoder\n\n decoder = BeamCTCDecoder(\n model.labels,\n lm_path=args.lm_path,\n alpha=args.alpha,\n beta=args.beta,\n cutoff_top_n=args.cutoff_top_n,\n cutoff_prob=args.cutoff_prob,\n beam_width=args.beam_width,\n num_processes=args.lm_workers,\n )\n else:\n decoder = GreedyDecoder(\n model.labels, blank_index=model.labels.index(\"_\")\n )\n\n spect_parser = SpectrogramParser(model.audio_conf, normalize=True)\n\n decoded_output, decoded_offsets = transcribe(\n audio_path=args.audio_path,\n spect_parser=spect_parser,\n model=model,\n decoder=decoder,\n device=device,\n use_half=args.half,\n )\n print(json.dumps(decode_results(decoded_output, decoded_offsets)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"255267288","text":"from django.core.management.base import BaseCommand\nfrom node.models import Node, IncomingNode\n\n\nclass Command(BaseCommand):\n help = 'Create a new incoming node'\n\n def add_arguments(self, parser):\n parser.add_argument('node_id')\n parser.add_argument('secret', nargs='?', default=Node.generate_secret())\n\n def handle(self, *args, **options):\n if IncomingNode.objects.filter(node_id=options['node_id']).exists():\n self.stdout.write(self.style.NOTICE(f'node with id {options[\"node_id\"]} already exists'))\n else:\n incoming_node = IncomingNode.objects.create(\n node_id=options['node_id'],\n secret=options['secret'],\n )\n\n self.stdout.write(self.style.SUCCESS('node successfully created'))\n self.stdout.write(f'node_id={incoming_node.node_id}')\n self.stdout.write(f'secret={incoming_node.secret}')\n","sub_path":"substrabac/node/management/commands/create_incoming_node.py","file_name":"create_incoming_node.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"475644527","text":"def main():\n num1=int(input())\n num2=int(input())\n num3=int(input())\n num4=int(input())\n comprehensive_list(num1,num2,num3,num4)\n \ndef comprehensive_list(num1,num2,num3,num4):\n nums=[num1,num2,num3]\n for c in range(0,num4):\n it=0\n it+=1\n for i in range(0,len(nums)):\n nums[i]=nums[i]-it\n if (sum_of_array(nums)=0:\n print(nums)\n transposition(nums) \n\ndef sum_of_array(nums):\n sum=0\n for i in range(0,len(nums)):\n sum=sum+nums[i]\n return sum\n\ndef transposition(nums):\n if nums[1]==nums[2] and nums[0]!=nums[1]: \n print(\"[\"+str(nums[1])+\", \"+str(nums[0])+\", \"+str(nums[2])+\"]\") \n print(\"[\"+str(nums[2])+\", \"+str(nums[1])+\", \"+str(nums[0])+\"]\") \n if nums[0]==nums[1] and nums[1]!=nums[2]:\n print(\"[\"+str(nums[0])+\", \"+str(nums[2])+\", \"+str(nums[1])+\"]\") \n print(\"[\"+str(nums[2])+\", \"+str(nums[1])+\", \"+str(nums[0])+\"]\") \nmain()","sub_path":"PythonLab7/hakerrank/pr8.py","file_name":"pr8.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"134361301","text":"# -*- coding:utf-8 -*-\n__author__ = 'studyer'\nfrom werkzeug.local import LocalProxy\nfrom daisy.cache import init_memcached\nfrom flask import current_app\n\n_memcached = None\n\n\ndef _create_memecached():\n global _memcached\n if _memcached is None:\n _memcached = init_memcached(current_app)\n return _memcached\n\n\nmemcached = LocalProxy(_create_memecached)\n","sub_path":"finance/helpers/cache_helper.py","file_name":"cache_helper.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"480996042","text":"import sys\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout, QVBoxLayout, QRadioButton, QInputDialog)\nfrom hyperparameters.hyperparameterConsts import DistanceAlgorithm\nfrom hyperparameters.hyperparametersState import CollaborativeHyperparametersState\n\nclass ParamsWidget(QtWidgets.QWidget):\n def __init__(self, width, height):\n super().__init__( flags = QtCore.Qt.Window )\n self.width = width\n self.height = height\n self.currentlyChosenAlgorithm = CollaborativeHyperparametersState().distanceAlgorithm\n self.initUI()\n \n def initUI(self):\n grid = QGridLayout()\n grid.setRowStretch(0, 1)\n grid.setRowStretch(1, 3)\n grid.setRowStretch(2, 3)\n grid.setRowStretch(3, 2)\n grid.setRowStretch(4, 3)\n grid.setRowStretch(5, 1)\n saveButton = QtWidgets.QPushButton(\"Zapisz i wyjdź\")\n saveButton.setObjectName(\"PlayerButton\") \n saveButton.setFixedSize(self.width*0.2, self.height*0.08)\n saveButton.clicked.connect(self.saveAndExit)\n grid.addWidget(saveButton, 4, 1)\n\n exitButton = QtWidgets.QPushButton(\"Wróć do menu\")\n exitButton.setObjectName(\"PlayerButton\") \n exitButton.setFixedSize(self.width*0.2, self.height*0.08)\n exitButton.clicked.connect(self.exitToMenu)\n grid.addWidget(exitButton, 1, 2)\n\n distanceLayout = self.getDistanceLayout()\n grid.addLayout(distanceLayout, 2, 1)\n\n neighboursLayout = self.getNeighboursLayout()\n grid.addLayout(neighboursLayout, 3, 1)\n \n self.setLayout(grid) \n self.show()\n\n def exitToMenu(self):\n self.window().showMenu()\n\n def saveAndExit(self):\n CollaborativeHyperparametersState().distanceAlgorithm = self.currentlyChosenAlgorithm\n print(\"setting distance {}\".format(self.currentlyChosenAlgorithm))\n n = self.nInput.text()\n if n and n.isdigit():\n print(\"setting number {}\".format(n))\n CollaborativeHyperparametersState().numberOfNeighbours = int(n)\n else:\n self.nInput.setText(CollaborativeHyperparametersState().numberOfNeighbours.__str__())\n self.window().showMenu()\n\n def algorithmSelectionChanged(self):\n radiobutton = self.sender()\n if radiobutton.isChecked():\n self.currentlyChosenAlgorithm = radiobutton.algorithm\n\n def getDistanceLayout(self):\n distanceBox = QGridLayout()\n distanceLabel = QLabel('Wybierz metodę obliczania dystansu')\n distanceLabel.setObjectName('ParamLabel')\n distanceBox.addWidget(distanceLabel, 0, 0)\n\n canberraRadiobutton = QRadioButton(\"Canberra Distance\")\n canberraRadiobutton.algorithm = DistanceAlgorithm.canberraDistance\n canberraRadiobutton.toggled.connect(self.algorithmSelectionChanged)\n self.setChecked(canberraRadiobutton)\n distanceBox.addWidget(canberraRadiobutton, 1, 0)\n\n euclideanRadiobutton = QRadioButton(\"Euclidean distance\")\n euclideanRadiobutton.algorithm = DistanceAlgorithm.euclideanDistance\n euclideanRadiobutton.toggled.connect(self.algorithmSelectionChanged)\n self.setChecked(euclideanRadiobutton)\n distanceBox.addWidget(euclideanRadiobutton, 3, 0)\n\n cosineDistanceRadiobutton = QRadioButton(\"Cosine distance\")\n cosineDistanceRadiobutton.algorithm = DistanceAlgorithm.cosineDistance\n cosineDistanceRadiobutton.toggled.connect(self.algorithmSelectionChanged)\n self.setChecked(cosineDistanceRadiobutton) \n distanceBox.addWidget(cosineDistanceRadiobutton, 2, 0)\n\n manhattanRadiobutton = QRadioButton(\"Manhattan distance\")\n manhattanRadiobutton.algorithm = DistanceAlgorithm.manhattanDistance\n manhattanRadiobutton.toggled.connect(self.algorithmSelectionChanged) \n self.setChecked(manhattanRadiobutton)\n distanceBox.addWidget(manhattanRadiobutton, 4, 0)\n\n chebyshevRadiobutton = QRadioButton(\"Chebyshev distance\")\n chebyshevRadiobutton.algorithm = DistanceAlgorithm.chebyshevDistance\n chebyshevRadiobutton.toggled.connect(self.algorithmSelectionChanged) \n self.setChecked(chebyshevRadiobutton)\n distanceBox.addWidget(chebyshevRadiobutton, 5, 0)\n\n return distanceBox\n\n def setChecked(self, radiobutton):\n currentlyCheckedAlgorithm = CollaborativeHyperparametersState().distanceAlgorithm\n if (radiobutton.algorithm == currentlyCheckedAlgorithm):\n radiobutton.setChecked(True)\n else: \n radiobutton.setChecked(False)\n\n def getNeighboursLayout(self):\n neighboursGrid = QVBoxLayout()\n label = QLabel('Wybierz n w n-nearest neighbours')\n label.setObjectName('ParamLabel')\n neighboursGrid.addWidget(label)\n\n self.nInput = QLineEdit()\n self.nInput.setObjectName('NInput')\n self.nInput.setValidator(QtGui.QIntValidator())\n self.nInput.setMaxLength(3)\n n = CollaborativeHyperparametersState().numberOfNeighbours.__str__()\n print(\"Current n: {}\".format(n))\n self.nInput.setText(n)\n neighboursGrid.addWidget(self.nInput)\n\n return neighboursGrid\n","sub_path":"widgets/paramsWidget.py","file_name":"paramsWidget.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"377216184","text":"from time import mktime\nfrom functools import wraps\nfrom flask import Flask, request, jsonify, session, flash, render_template, make_response\nimport datetime\nimport jwt\nimport requests\n\nfrom secrets import api_auth_token, jwt_secret_key\nfrom utils import parse_date_time\nfrom business import get_user_by_email\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = jwt_secret_key\n\n#TODO still manually adding the token to the url. that seesm wrong.\n#TODO clean up code once it all works\n#TODO make sure wraps are working and appropriate\n#TODO reduce duplication\n#TODO comment code\n\n#pretty sure this works as expected\ndef decode_auth_token(auth_token):\n return jwt.decode(auth_token, app.config['SECRET_KEY'])\n\n#pretty sure this works as expected\ndef encode_auth_token(user_id, name, email, scope):\n return jwt.encode(\n payload = {\n 'sub': user_id,\n 'name': name,\n 'email': email,\n 'scope': scope,\n 'exp': mktime((datetime.datetime.now() + datetime.timedelta(days=1)).timetuple())\n },key=app.config['SECRET_KEY'], algorithm=\"HS256\")#.decode(\"utf-8\")\n\n#TODO make this work wih Bearer token auth\ndef get_user_from_token(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n #token = request.headers.get('Authorization': 'Bearer ')\n token = request.args.get('token')\n if not token:\n return jsonify({'messaage' : 'missing token'}), 403\n try:\n data = decode_auth_token(token, app.config['SECRET_KEY'])\n return data\n except:\n return jsonify({'message': 'invalid token'}), 403\n return func(*args, **kwargs)\n return wrapped\n\n#TODO more testing, seems inconsistent\n@app.route('/')\ndef index():\n if not session.get('logged_in'):\n return render_template('login.html')\n else:\n return \"Currently not logged in\"\n\n#TODO more testing. not sure if this works properly or is even needed\n@app.route('/authorized')\n@get_user_from_token\ndef authorized():\n return 'this is the authorized view, cant get here without a token'\n\n\n#TODO testing. also: # get the user data from the auth/header/jwt\n@app.route('/user', methods=['GET'])\ndef user():\n token = request.args.get('token')\n try:\n user = jwt.decode(token, app.config['SECRET_KEY'])\n except: \n return jsonify({'message': \"token invald\"})\n return {\n 'user_id': user['sub'],\n 'name': user['name'],\n 'email': user['email']\n }\n\n#TODO use flask.request to get the json body and get the email and scopes property\n@app.route('/login', methods=['POST'])\ndef login():\n if request.form['email']:\n user = get_user_by_email(request.form['email'])\n session['logged_in'] = True\n token = encode_auth_token(user_id = user['id'], name = user['name'], email = user['email'], scope=[\"openid\"])\n # return token\n return {'token': token}\n else:\n return make_response(\"unable to verify user\", 403, {'WWW-Authenticate': 'Basic-Realm=\"Login Required\"'})\n\n#API request works, some of the date time stuff doesn't. need to test the route itself\n@app.route('/widgets', methods=['GET'])\ndef widgets(type = None, created_start = None, created_end = None):\n url = \"https://us-central1-interview-d93bf.cloudfunctions.net/widgets?user_id={user_id}\"\n headers = {'Authorization': 'apikey '+api_auth_token, 'Content-Type': 'application/json'}\n res = requests.get(url, headers = headers, data = query)\n res_dict = json.loads(res.content)\n parsed_result = parse_dict(res_dict)\n filtered_result = filter_result(parsed_result, type, created_start, created_end)\n return {\n 'total_widgets_own_by_user': len(filtered_result),\n 'matching_items': filtered_result\n }\n\n#TODO fix parse_date_time issue\ndef parse_dict(res_dict):\n import re\n for item in res_dict:\n type_label = re.sub(r'-', \" \", item['type']).title()\n item['type_label'] = type_label\n item['created'] = parse_date_time(item['created'])\n return res_dict\n\n#TODO create_start and create_end need work. I tried removing the item instead of passing but that wasn't working. \ndef filter_result(parsed_result, type = None, created_start = None, created_end = None):\n filtered_result=[]\n for item in parsed_result:\n if type and item['type'] != type:\n pass\n elif created_start and item['created'] != created_start:\n pass\n elif created_end and item['created'] != created_end:\n pass\n else:\n print(item['type'])\n filtered_result.append(item)\n print(filtered_result)\n return filtered_result\n\nif __name__ == '__main__':\n app.run()\n ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"304991428","text":"import glob\nimport os\nimport tensorflow.compat.v1 as tf\ngfile = tf.io.gfile\n\ndef init(module, weight_init, bias_init, gain=1):\n weight_init(module.weight.data, gain=gain)\n bias_init(module.bias.data)\n return module\n\ndef cleanup_log_dir(log_dir):\n try:\n gfile.makedirs(log_dir)\n except OSError:\n files = glob.glob(os.path.join(log_dir, '*.monitor.csv'))\n for f in files:\n os.remove(f)\n","sub_path":"ucb_rl2_meta/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"576983744","text":"\"\"\"\nThis module contains common utility functions for work with pseudomotors used in Solaris beamlines\n\"\"\"\n\n\ndef get_physical_motors(macro, pseudo_controller_name):\n \"\"\"Obsolete function, use 'get_physical_motors_list' instead.\"\"\"\n ctl = macro.getController(pseudo_controller_name)\n\n elements = ctl.read_attribute(\"ElementList\").value\n phys_motors = set()\n\n for e in elements:\n pseudo = macro.getPseudoMotor(e)\n\n physicals = pseudo.get_property(\"elements\")[\"elements\"]\n phys_motors = phys_motors.union(map(int, physicals))\n\n physical_names = [x.name for x in macro.getMotors().itervalues() if x.id in phys_motors]\n return physical_names\n\n\ndef get_physical_motors_list(macro, pseudo_ctrl):\n \"\"\"\n The functions finds a list of all physical motors, used by pseudomotor controller\n \"\"\"\n # obtaining controller's elements (pseudo motors)\n pool = pseudo_ctrl.getPoolObj()\n pseudo_motors = []\n for _, elem in pool.getElementsOfType(pseudo_ctrl.getMainType()).items():\n if elem.controller != pseudo_ctrl.getFullName():\n continue\n pseudo_motors.append(elem)\n\n # obtaining pm's physical motors\n motors = []\n for pm in pseudo_motors:\n motors.extend(pm.elements)\n\n # getting rid of duplicates\n motors = set(motors)\n return list(motors)\n","sub_path":"src/solaris_sardana_utils/pseudomotors.py","file_name":"pseudomotors.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"344510407","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n# 导入Django函数logout()\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib.auth.forms import UserCreationForm\n\n\n# Create your views here.\n\n# 命名为logout_view()旨在将其与从Django中调用的logout()区分\ndef logout_view(request):\n \"\"\"注销用户\"\"\"\n logout(request)\n return HttpResponseRedirect(reverse('learning_log:index'))\n\n\ndef register(request):\n \"\"\"注册新用户\"\"\"\n if request.method != 'POST':\n \"\"\"显示空的注册表\"\"\"\n form = UserCreationForm()\n else:\n # 处理填好的表单\n form = UserCreationForm(data=request.POST)\n\n if form.is_valid():\n new_user = form.save()\n # 让用户自动登录,再重定向到主页\n authenticated_user = authenticate(username=new_user.username,\n password=request.POST['password1'])\n login(request, authenticated_user)\n return HttpResponseRedirect(reverse('learning_log:index'))\n\n context = {'form': form}\n return render(request, 'users/register.html', context)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"520426832","text":"#import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport math\nimport copy\n\nclass ScheduleEnvironment(object):\n # This class models the schedule-environment\n # it saves the times, machines and stages of each heat and simulates steps through the state space;\n # a step is the movement of the next free heat to the next stage (except on stage 4, where all heats are scheduled\n # in one step)\n # also, this class checks after each step, which actions can be taken from the current state,\n # so that the schedule is still feasible; only these actions can be chosen from the respective stage;\n # further, this class has a method for the graphical rendering of the schedule\n\n def __init__(self, num_heats, rounds):\n # constructor\n\n # variables for testing, output, analysis\n self.rounds = rounds # only for testing reasons\n\n # save the start and end times of heats on each machine; necessary for rendering\n self.heat_seq_out = []\n self.mach_out = []\n self.start_times = []\n self.tau_out = []\n\n # visible state --> List, which contains for each machine on next stage , when it will be free again\n # uses relative times --> times are given from the perspective of the next free heat\n # the part of the state-information, which is visible to the agent\n self.vis_state = [0, 0]\n\n #actions\n self.all_actions = [0, 1] # all actions, that can be taken in general\n self.poss_actions = [0, 1] # actions, that can be taken without rendering the schedule infeasible\n\n # additional state information, invisible to agent\n\n # save for each stage and machine the sequence of heats\n self.heat_seq_stage_mach = [[[]], [[], []], [[], []], [[], []], [[], []]]\n # save for each heat which machine it is processed on on each stage; each entry in a heats-list represents\n # a stage; the lists are ordered in the sequence of the stages\n self.mach_of_heat_and_stage = [[0] for heat in range(num_heats)]\n # save for each heat on each stage the start time t_start and the processing time tau[t_start, tau]\n self.times_of_heat_stage = [[[0, 0]] for heat in range(num_heats)]\n\n # times_of_heat_stage - variants for actions left and right;\n # these lists are overwritten after each step for those actions, that lead to a feasible schedule\n # when an action is taken, the corresponding table is used to overwrite the main table times_of_heat_stage\n self.times_of_heat_stage_left = [[[0, 0]] for heat in range(num_heats)]\n self.times_of_heat_stage_right = [[[0, 0]] for heat in range(num_heats)]\n\n # Parameters\n\n # number of heats to be scheduled\n self.num_heats = num_heats\n # minimum processing times tau for each machine on each stage\n self.tau_low_stage_mach = [[0], [85, 85], [8, 8], [45, 45], [60, 60]]\n # maximum possible tau\n self.tau_max_stage_mach = [[0], [100, 100], [20, 20], [60, 60], [80, 80]]\n # setup times times for each machine on each stage\n self.t_s_stage_mach = [[0], [9, 9], [5, 5], [15, 5], [0, 0]]\n # clean-up times times for each machine on each stage\n self.t_cl_stage_mach = [[0], [9, 9], [5, 5], [15, 5], [0, 0]]\n # maximum transfer time for stage 0 --> is calculated as a number, that never is met;\n # because stage 0 ist the buffer in front of the first stage and therefore has unlimited transfer time\n self.t_tr_max_stage_0 = self.num_heats * (max(self.tau_max_stage_mach[1][0], self.tau_max_stage_mach[1][1])\n + max(self.t_s_stage_mach[1][0], self.t_s_stage_mach[1][1])\n + max(self.t_cl_stage_mach[1][0], self.t_cl_stage_mach[1][1]))\n # maximum transfer or hold-up time of a heat between consecutive stages\n self.t_tr_max_stage = [self.t_tr_max_stage_0, 30, 5, 20, 0]\n\n # Initialize first set of possible actions and times_of_heat_stage - variants; necessary for the first step\n self.set_poss_actions_stages_1_to_3()\n return\n\n # get-methods\n\n def get_t_free_total_stage_mach(self, stage, mach):\n # return the total time, at which the given machine on the given stage is free again for processing the next heat\n t_free_total = 0\n for heat, stages_list in enumerate(self.copy_times_of_heat_stage_complete()):\n # check for each heat\n if len(stages_list) > stage:\n # is heat processed on given stage?\n if (self.get_mach_of_heat_and_stage(heat, stage) == mach):\n # is heat processed on given machine?\n heat_stage_times = stages_list[stage]\n t_mach_ready = heat_stage_times[0]+heat_stage_times[1] + self.get_t_cl_stage_mach(stage, mach)\\\n + self.get_t_s_stage_mach(stage, mach)\n if t_free_total < t_mach_ready:\n t_free_total = t_mach_ready\n\n return t_free_total\n\n def get_times_of_heat_stage(self, heat, stage):\n # return list with start time and processing time for one specific heat and one specific stage\n return self.times_of_heat_stage[heat][stage][:]\n\n def get_mach_of_heat_and_stage(self, heat, stage):\n # return the machine, which the given heat is processed on on the given stage\n return self.mach_of_heat_and_stage[heat][stage]\n\n def get_num_heats(self):\n # return the total number of heats, that are to be scheduled in this environment\n return len(self.times_of_heat_stage)\n\n def get_tau_low_stage_mach(self, stage, mach):\n # return for a given stage and machine the minimum processing time tau_low\n return self.tau_low_stage_mach[stage][mach]\n\n def get_t_s_stage_mach(self, stage, mach):\n # return for a given stage and machine the setup time t_s\n return self.t_s_stage_mach[stage][mach]\n\n def get_t_cl_stage_mach(self, stage, mach):\n # return for a given stage and machine the clean-up time t_cl\n return self.t_cl_stage_mach[stage][mach]\n\n def get_t_tr_max_stage(self, stage):\n # return for a given stage the maximum transfer time t_tr_max\n return self.t_tr_max_stage[stage]\n\n def get_tau_max(self, stage, mach):\n # return for a given stage and machine the maximum processing time tau_max\n return self.tau_max_stage_mach[stage][mach]\n\n def get_poss_actions(self):\n # return all actions, that can be taken next by the agent without rendering the schedule infeasible\n return self.poss_actions\n\n def get_heat_seq_stage_mach(self, stage, mach):\n # return the sequence of heats, that are processed on the given stage and machine\n return self.heat_seq_stage_mach[stage][mach]\n\n def get_t_free_total_heat(self, heat):\n # return the total time, at which the given heat is free again for being processed on the next stage\n t_free_total = self.get_times_of_heat_stage(heat, -1)[0] + self.get_times_of_heat_stage(heat, -1)[1]\n return t_free_total\n\n def get_curr_stage_of_heat(self, heat):\n # return the stage, on which the given heat is being processed currently\n return len(self.times_of_heat_stage[heat]) - 1\n\n def get_next_free_heat(self):\n # return the next free heat --> heat, the processing of which is finished next which thus is ready for being\n # scheduled next\n t_free_heat_stages_0_to_2 = [self.get_t_free_total_heat(heat) for heat in range(self.get_num_heats())\\\n if self.get_curr_stage_of_heat(heat) < 3]\n heats_stages_0_to_2 = [heat for heat in range(self.get_num_heats()) if self.get_curr_stage_of_heat(heat) < 3]\n if not t_free_heat_stages_0_to_2:\n return None, True\n else:\n return heats_stages_0_to_2[t_free_heat_stages_0_to_2.index(min(t_free_heat_stages_0_to_2))], False\n\n def get_vis_state(self):\n # return the part of the current state, which is visible to the agent --> relative times from the view of the\n # next free heat, when each machine on the next stage (from the view of the next free heat) is free again for\n # processing\n return self.vis_state[:]\n\n def get_all_consec_heats_on_machine(self, heat, stage, mach):\n # return all consecutive heats after the given heat on the given stage and machine\n heat_seq = self.get_heat_seq_stage_mach(stage, mach)\n consec_heats = heat_seq[heat:]\n return consec_heats\n\n # set-methods\n\n def set_heat_seq_stage_mach(self, stage, mach, heat):\n # appends the given heat to the heat sequence n the given machine and stage\n self.heat_seq_stage_mach[stage][mach].append(heat)\n return\n\n def set_vis_state(self, next_free_heat):\n # set the visible state for the given next free heat\n # not used in following cases: Next state is terminal or infeasible; Next stage of next_free_heat is stage 4\n next_stage = self.get_curr_stage_of_heat(next_free_heat) + 1\n t_free_next_free_heat = self.get_t_free_total_heat(next_free_heat)\n self.vis_state[0] = max(self.get_t_free_total_stage_mach(next_stage, 0) - t_free_next_free_heat, 0)\n self.vis_state[1] = max(self.get_t_free_total_stage_mach(next_stage, 1) - t_free_next_free_heat, 0)\n return\n\n def set_vis_state_terminal(self):\n # set the visible state to the terminal stage [-1, -1]\n self.vis_state = [-1, -1]\n return\n\n def set_vis_state_stage_four(self):\n # set the visible state to [0, 0]\n # used, when the next stage to be scheduled is stage 4\n self.vis_state = [0, 0]\n return\n\n def set_vis_state_infeasible(self):\n # set the visible state to the infeasible state [-2, -2]\n self.vis_state = [-2, -2]\n return\n\n def set_times_of_heat_stage_complete(self, times):\n # overwrite ALL ACTUAL times of ALL heats on ALL stages with the values given in times\n self.times_of_heat_stage = copy.deepcopy(times)\n return\n\n def set_times_of_heat_stage_action_complete(self, times, action):\n # overwrite ALL HYPOTHETICAL times - if the given action would be taken - of ALL heats on ALL stages with\n # the values given in times\n if action == 0:\n self.times_of_heat_stage_left = copy.deepcopy(times)\n else:\n self.times_of_heat_stage_right = copy.deepcopy(times)\n return\n\n # supportive methods for performance of steps and choice of possible actions\n\n def copy_times_of_heat_stage_complete(self):\n # return complete copy of list times_of_heat_stage, which saves ACTUAL start times and processing times\n # for all heats and stages\n times_copy = copy.deepcopy(self.times_of_heat_stage)\n return times_copy\n\n def copy_times_of_heat_stage_action_complete(self, action):\n # return complete copy of list times_of_heat_stage_left or list times_of_heat_stage_right, which save for all\n # heats and stages HYPOTHETICAL start times and processing times in case action 0 or action 1 is taken next\n if action == 0:\n times_copy = copy.deepcopy(self.times_of_heat_stage_left)\n else:\n times_copy = copy.deepcopy(self.times_of_heat_stage_right)\n\n return times_copy\n\n def add_next_mach_of_heat(self, heat, mach):\n # save for the given heat the machine, on which it is processed on the next stage\n self.mach_of_heat_and_stage[heat].append(mach)\n return\n\n def add_stage_and_times_of_heat(self, times, heat):\n # save for the given heat the given times on the next stage\n self.times_of_heat_stage[heat].append(times)\n return\n\n # methods related with the determination of the processing and start times of heats in the context of\n # the fulfillment of transfer times\n\n def calc_tau_nec(self, heat, stage, times_of_heat_stage_copy):\n # calculate the necessary tau of the given heat on the given stage to fulfill t_tr\n # by the start_time on the next stage\n mach_given_stage = self.get_mach_of_heat_and_stage(heat, stage)\n start_time_next_stage = times_of_heat_stage_copy[heat][stage+1][0]\n start_time_given_stage = times_of_heat_stage_copy[heat][stage][0]\n t_tr_max_given_stage = self.get_t_tr_max_stage(stage)\n tau_low_mach_given_stage = self.get_tau_low_stage_mach(stage, mach_given_stage)\n tau_nec = start_time_next_stage - start_time_given_stage - t_tr_max_given_stage\n return tau_nec\n\n def calc_new_start_times_after_tau_changed(self, start_heat, stage, times_of_heat_stage_copy):\n # calculate new start times of all heats on a given stage, after a tau of a heat on this stage\n # has been changed\n mach = self.get_mach_of_heat_and_stage(start_heat, stage)\n heat_seq_complete = self.get_heat_seq_stage_mach(stage, mach)\n heat_seq = heat_seq_complete[heat_seq_complete.index(start_heat):]\n # Anmerkung: hier kann ich auch die Methode get_consec_heats verwenden!\n for i in range(len(heat_seq)-1):\n start_time_new = max(times_of_heat_stage_copy[heat_seq[i+1]][stage][0],\n times_of_heat_stage_copy[heat_seq[i]][stage][0]\n + times_of_heat_stage_copy[heat_seq[i]][stage][1]\n + self.get_t_cl_stage_mach(stage, mach) + self.get_t_s_stage_mach(stage, mach))\n times_of_heat_stage_copy[heat_seq[i+1]][stage][0] = start_time_new\n\n return times_of_heat_stage_copy\n\n def calc_and_apply_tau_nec(self, heat, stage, times_of_heat_stage_copy):\n # calculate for the given heat on the given stage the necessary processing time tau of the heat to fulfill\n # the transfer time t_tr of the stage by the start time on the next stage; then apply the necessary tau and\n # adjust all start times of consecutive heats the stage\n times_of_heat_stage_copy[heat][stage][1] = self.calc_tau_nec(heat, stage, times_of_heat_stage_copy)\n times_of_heat_stage_copy = self.calc_new_start_times_after_tau_changed(heat, stage, times_of_heat_stage_copy)\n\n return times_of_heat_stage_copy\n\n def check_t_tr_fulfilled(self, heat, stage, times_of_heat_stage_copy):\n # check, if the transfer time t_tr of the given stage is fulfilled for the given heat by its start time of\n # the consecutive stage\n is_fulfilled = True\n t_start_next_stage = times_of_heat_stage_copy[heat][stage+1][0]\n end_time_given_stage = times_of_heat_stage_copy[heat][stage][0]\\\n + times_of_heat_stage_copy[heat][stage][1]\n\n if end_time_given_stage + self.get_t_tr_max_stage(stage) < t_start_next_stage:\n is_fulfilled = False\n\n return is_fulfilled\n\n def check_change_tau_t_tr_fulfillable(self, heat, stage, times_of_heat_stage_copy):\n # should be called after check_t_tr_fulfilled;\n # check, if the transfer time t_tr of the given heat on the given stage is fulfillable by the start time on\n # the consecutive stage by changing tau of the heat on the given stage\n\n is_fulfillable = True\n mach_given_stage = self.get_mach_of_heat_and_stage(heat, stage)\n t_start_next_stage = times_of_heat_stage_copy[heat][stage+1][0]\n if (times_of_heat_stage_copy[heat][stage][0] + self.get_tau_max(stage, mach_given_stage)\n + self.get_t_tr_max_stage(stage) < t_start_next_stage):\n is_fulfillable = False\n\n return is_fulfillable\n\n def change_tau_and_check_all_t_tr_fulfillable(self, start_heat, start_stage, times_of_heat_stage_copy):\n # is used, if t_tr on a stage for a heat is not fulfilled, but fulfillable;\n # calculate and apply the new processing time tau for the start heat on the start stage and check if\n # the transfert time t_tr of the start stage is fulfillable by the start time of the heat on the next stage;\n # then check, if the schedule is still feasible regarding t_tr for ALL heats on ALL stages\n\n t_tr_fulfillable_for_all_heats = True\n start_mach = self.get_mach_of_heat_and_stage(start_heat, start_stage)\n\n # calculate and apply necessary tau to first heat in sequence on start stage\n times_of_heat_stage_copy = self.calc_and_apply_tau_nec(start_heat, start_stage, times_of_heat_stage_copy)\n\n # check for each consecutive heat on stage, if t_tr of PREVIOUS stage is still fulfillable after\n # changing of start_times\n # workflow: check, if t_tr is fulfilled; if not: check, if it is fulfillable; if not:\n # apply new tau, adjust all start_times influenced by new tau; check again, if fulfilled;\n # repeat for all heats on all stages\n heat_seq = self.get_heat_seq_stage_mach(start_stage, start_mach)[start_heat:]\n for heat in heat_seq:\n if not self.check_t_tr_fulfilled(heat, start_stage-1, times_of_heat_stage_copy):\n if not self.check_change_tau_t_tr_fulfillable(heat, start_stage - 1, times_of_heat_stage_copy):\n # if t_tr is not fulfillabe for one heat, return False\n t_tr_fulfillable_for_all_heats = False\n return t_tr_fulfillable_for_all_heats, times_of_heat_stage_copy\n else:\n times_of_heat_stage_copy = self.calc_and_apply_tau_nec(heat, start_stage - 1,\n times_of_heat_stage_copy)\n\n # check for each heat on each previous stage, if t_tr is still fulfillable after changing of start_times\n for stage in range(max(start_stage-2, 0), 0, -1):\n for mach in range(1):\n heat_seq_mach = self.get_heat_seq_stage_mach(stage, mach)\n for heat in heat_seq_mach:\n if not self.check_t_tr_fulfilled(heat, stage, times_of_heat_stage_copy):\n if not self.check_change_tau_t_tr_fulfillable(heat, stage, times_of_heat_stage_copy):\n # if t_tr is not fulfillabe for one heat, return False\n t_tr_fulfillable_for_all_heats = False\n return t_tr_fulfillable_for_all_heats, times_of_heat_stage_copy\n else:\n times_of_heat_stage_copy = self.calc_and_apply_tau_nec(heat, stage,\n times_of_heat_stage_copy)\n\n return t_tr_fulfillable_for_all_heats, times_of_heat_stage_copy\n\n def calc_t_start_nec(self, heat, stage, times_of_heat_stage_copy):\n # calculate for the given heat and stage, whichstart time t_start on the next stage is necessary to fulfill\n # the transfer time t_tr of the given stage, given, that the maximum tau is used\n t_start_nec = times_of_heat_stage_copy[heat][stage+1][0] - self.get_t_tr_max_stage(stage)\\\n - self.get_tau_max(stage, self.get_mach_of_heat_and_stage(heat, stage))\n\n return t_start_nec\n\n def check_change_t_start_collision_free(self, heat, stage, times_of_heat_stage_copy):\n # should be called after check_t_tr_fulfilled;\n # check, if the transfer time t_tr of the given heat on the given stage is fulfillable by the start_time\n # on the next stage by changing the processing time tau of the heat on the given stage\n\n collision_free = True\n mach_given_stage = self.get_mach_of_heat_and_stage(heat, stage)\n heat_seq_mach = self.get_heat_seq_stage_mach(stage, mach_given_stage)\n if not heat_seq_mach.index(heat) == len(heat_seq_mach)-1:\n following_heat = heat_seq_mach[heat_seq_mach.index(heat)+1]\n if times_of_heat_stage_copy[following_heat][stage][0]\\\n < self.calc_t_start_nec(heat, stage, times_of_heat_stage_copy) + \\\n self.get_tau_max(stage, mach_given_stage) + self.get_t_s_stage_mach(stage, mach_given_stage) \\\n + self.get_t_cl_stage_mach(stage, mach_given_stage):\n collision_free = False\n\n return collision_free\n\n def calc_and_set_t_start_new(self, heat, stage, times_of_heat_stage_copy):\n # calculate new t_start for the given heat and stage in order to fulfill the transfer time t_tr of the stage;\n # use tau_max of the stage and machine to minimize the change of t_start\n # comment: this prioritization may be changed in later versions, so that at first a change in start time is\n # checked and performed, before a change in the processing time is considered\n t_start_new = self.calc_t_start_nec(heat, stage, times_of_heat_stage_copy)\n times_of_heat_stage_copy[heat][stage][0] = t_start_new\n times_of_heat_stage_copy[heat][stage][1] = self.get_tau_max(stage, self.get_mach_of_heat_and_stage(heat, stage))\n return times_of_heat_stage_copy\n\n # Methods for the determination of possible actions, which, when performed, lead to a feasible schedule\n # A distinction is made between the actions for the for the scheduling of the stages 1 to 3 and the actions\n # for stage 4\n\n def set_poss_actions_stages_1_to_3(self):\n # check, for which machines on the next stage the transfer time t_tr_max is fulfillable;\n # only those machines can be chosen as actions during the next step;\n # always check in this order:\n # t_tr_fulfilled? -- no --> t_tr_fulfillable by change of process time on previous stage?\n # -- no --> t_tr_fulfillable by change of start time on previous stage?\n # if no actions are possible, an empty list is returned;\n # used for setting of actions for the scheduling of stages 1 to 3\n\n self.poss_actions = []\n\n # generate 2 copies of the times for each heat and stage,\n # to simulate the 2 scenarios of taking each action\n times_of_heat_stage_copy_left = self.copy_times_of_heat_stage_complete()\n times_of_heat_stage_copy_right = self.copy_times_of_heat_stage_complete()\n\n # check for next_free_heat:\n # first case: taking action 0 (left machine on next stage)\n # second case: taking action 1 (right machine on next stage)\n next_free_heat, _ = self.get_next_free_heat()\n curr_stage = self.get_curr_stage_of_heat(next_free_heat)\n times_of_heat_stage_copy_left[next_free_heat].append(\n [self.get_t_free_total_heat(next_free_heat) + self.get_vis_state()[0],\n self.get_tau_low_stage_mach(curr_stage + 1, 0)])\n times_of_heat_stage_copy_right[next_free_heat].append(\n [self.get_t_free_total_heat(next_free_heat) + self.get_vis_state()[1],\n self.get_tau_low_stage_mach(curr_stage + 1, 1)])\n\n # check, if action 0 (left machine) is feasible\n # if and elif: view onto the next stage; check compliance with t_tr of current stage\n if self.check_t_tr_fulfilled(next_free_heat, curr_stage, times_of_heat_stage_copy_left):\n self.poss_actions.append(0)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_left, 0)\n\n # check, if a change in tau can lead to the fulfillment of t_tr of the stage\n elif self.check_change_tau_t_tr_fulfillable(next_free_heat, curr_stage, times_of_heat_stage_copy_left):\n # view back to all previous stages; check compliance with t_tr of all previous stages\n all_t_tr_fulfillable, times_of_heat_stage_copy_left = \\\n self.change_tau_and_check_all_t_tr_fulfillable(next_free_heat, curr_stage, times_of_heat_stage_copy_left)\n\n if all_t_tr_fulfillable == True:\n self.poss_actions.append(0)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_left, 0)\n\n # check, if a change of the start time can lead to the fulfillment of t_tr of the stage, without\n # interfering with the start time of the consecutive heat\n elif self.check_change_t_start_collision_free(next_free_heat, curr_stage, times_of_heat_stage_copy_left):\n times_of_heat_stage_copy_left = self.calc_and_set_t_start_new(next_free_heat, curr_stage,\n times_of_heat_stage_copy_left)\n self.poss_actions.append(0)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_left, 0)\n\n # check, if action 1 (right machine) is feasible\n # if and elif: view onto the next stage; check compliance with t_tr of current stage\n if self.check_t_tr_fulfilled(next_free_heat, curr_stage, times_of_heat_stage_copy_right):\n self.poss_actions.append(1)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_right, 1)\n elif self.check_change_tau_t_tr_fulfillable(next_free_heat, curr_stage, times_of_heat_stage_copy_right):\n # view back to all previous stages; check compliance with t_tr of all previous stages\n all_t_tr_fulfillable, times_of_heat_stage_copy_right = \\\n self.change_tau_and_check_all_t_tr_fulfillable(next_free_heat, curr_stage,\n times_of_heat_stage_copy_right)\n\n if all_t_tr_fulfillable == True:\n self.poss_actions.append(1)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_right, 1)\n\n # check, if a change of the start time can lead to the fulfillment of t_tr of the stage, without\n # interfering with the start time of the consecutive heat\n elif self.check_change_t_start_collision_free(next_free_heat, curr_stage, times_of_heat_stage_copy_right):\n times_of_heat_stage_copy_right = self.calc_and_set_t_start_new(next_free_heat, curr_stage,\n times_of_heat_stage_copy_right)\n self.poss_actions.append(1)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy_right, 1)\n\n return\n\n def set_poss_actions_stage_4(self):\n # used for setting of actions for stage 4 while ensuring both continuous casting and the correct casting seq\n # check, how the heats can be scheduled on stage 4 without violating the transfer time of stage 3 and without\n # starting the processing, before a heat has been finished of stage 3; Check all options and save for a\n # possible action the best configuration (regarding the makespan); when this action is chosen, automatically\n # the best scheduling is done for this machine\n # annotation: at the moment, both casters are identical --> thus, there is no difference, on which caster\n # the heats are being processed; the check is therefore done only for one caster and if the check\n # is positive, both actions are added to possible_actions\n\n self.poss_actions = []\n times_list = [] # save times_of_heat_stage for each feasible solution; later select best one\n\n # check all possibilities for all heats and for taking action 0 (left machine on next stage)\n poss_start_times_stage_4 = []\n all_heats = [heat for heat in range(self.get_num_heats())]\n is_feasible = True\n\n for heat_1 in all_heats:\n # for each heat a test is done, if it is possible to schedule all heats on stage 4 in the desired sequence\n # and continuously, when setting the start time of the heat on stage 4 to the time at which it is finished\n # on stage 3; this corresponds to putting the heats in the correct casting sequence and then moving the\n # complete sequence as far as possible to the left on the time axis; all feasible outcomes are saved and\n # later the one with the shortest makespan is selected\n\n # generate 1 copy of the times for each heat and stage\n previous_heats = all_heats[:all_heats.index(heat_1)]\n following_heats = all_heats[all_heats.index(heat_1):]\n following_heats.remove(heat_1)\n times_of_heat_stage_copy = self.copy_times_of_heat_stage_complete()\n t_start_stage_4 = self.get_t_free_total_heat(heat_1)\n times_of_heat_stage_copy[heat_1].append([t_start_stage_4, self.get_tau_low_stage_mach(4, 0)])\n t_start_next_heat = t_start_stage_4 + self.get_tau_low_stage_mach(4, 0)\n t_start_stage_4 -= self.get_tau_low_stage_mach(4, 0)\n\n # check, if all heats following after heat_1 can be scheduled on stage 4 while maintaining feasibility\n is_feasible, times_of_heat_stage_copy = \\\n self.check_stage_4_following_heats(t_start_next_heat, following_heats, times_of_heat_stage_copy)\n if is_feasible:\n # check, if all heats preceding heat_1 can be scheduled on stage 4 while maintaining feasibility\n is_feasible, t_start_stage_4, times_of_heat_stage_copy = \\\n self.check_stage_4_previous_heats(t_start_stage_4, previous_heats, times_of_heat_stage_copy)\n\n # after all necessary changes to tau on stage 3 have been made, a last check must be done to all heats,\n # if the heats are free to be processed on their starting time on stage 4\n if is_feasible:\n is_feasible = self.last_check_stage_4(all_heats, times_of_heat_stage_copy)\n\n # if the heat sequence with the proposed start time did pass all tests, include it into the list of\n # possible start times; also remember the start- and processing times, that were calculated for this case\n if is_feasible:\n poss_start_times_stage_4.append(t_start_stage_4)\n times_list.append(times_of_heat_stage_copy)\n\n # from all possible heat sequences, chose the one, that has the earliest start time\n # in order to minimize the makespan\n if len(poss_start_times_stage_4) > 0:\n t_start_stage_4_min = min(poss_start_times_stage_4)\n index = poss_start_times_stage_4.index(t_start_stage_4_min)\n times_of_heat_stage_copy = times_list[index]\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy, 0)\n self.set_times_of_heat_stage_action_complete(times_of_heat_stage_copy, 1)\n self.poss_actions.append(0)\n self.poss_actions.append(1)\n\n return\n\n def check_stage_4_following_heats(self, t_start_next_heat, following_heats, times_of_heat_stage_copy):\n # support function for schedule_stage_4\n # after choosing a hypothetical position for a heat on stage 4, check for all consecutively casted heats,\n # if they are free for casting when needed, and if t_tr is fulfilled\n is_feasible = True\n for heat_2 in following_heats:\n times_of_heat_stage_copy[heat_2].append([t_start_next_heat, self.get_tau_low_stage_mach(4, 0)])\n if t_start_next_heat < self.get_t_free_total_heat(heat_2):\n # check, if continuous casting is possible: next heat has to be finished on stage 3\n # when the current heat is finished on stage 4\n is_feasible = False\n break\n\n elif not self.check_t_tr_fulfilled(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr of last stage is fulfilled for heat_2\n if self.check_change_tau_t_tr_fulfillable(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr is fulfillable on all PREVIOUS stages\n all_t_tr_fulfillable, times_of_heat_stage_copy = \\\n self.change_tau_and_check_all_t_tr_fulfillable(heat_2, 3,\n times_of_heat_stage_copy)\n if not all_t_tr_fulfillable:\n is_feasible = False\n break\n\n t_start_next_heat += self.get_tau_low_stage_mach(4, 0)\n\n # check (from back to forth), if there are still not-fulfilled t_tr; check, if these t_tr can be fulfilled\n # by changes in start times combined with use of maximum tau\n # back to forth is better, because more spaces in the schedule can be used\n if is_feasible:\n for heat_2 in reversed(following_heats):\n if not self.check_t_tr_fulfilled(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr of last stage is fulfilled for heat_2\n if self.check_change_t_start_collision_free(heat_2, 3, times_of_heat_stage_copy):\n times_of_heat_stage_copy = self.calc_and_set_t_start_new(heat_2, 3,\n times_of_heat_stage_copy)\n else:\n is_feasible = False\n break\n\n return is_feasible, times_of_heat_stage_copy\n\n def check_stage_4_previous_heats(self, t_start_stage_4, previous_heats, times_of_heat_stage_copy):\n # support method for schedule_stage_4;\n # after choosing a hypothetical position for a heat on stage 4 and testing all following heats,\n # check for all previous heats if they are free for the processing on stage 4 when needed,\n # and if t_tr is fulfilled\n\n # first, check if heats are free for casting\n is_feasible = True\n for heat_2 in reversed(previous_heats):\n times_of_heat_stage_copy[heat_2].append(\n [t_start_stage_4, self.get_tau_low_stage_mach(4, 0)])\n if t_start_stage_4 < self.get_t_free_total_heat(heat_2):\n # check, if continuous casting is possible: next heat has to be finished on stage 3\n # when the current heat is finished on stage 4\n is_feasible = False\n break\n\n t_start_stage_4 -= self.get_tau_low_stage_mach(4, 0)\n\n # check, if all t_tr are fulfilled\n # done from early to late start times, because changes in process times can resolve conflicts\n # in t_tr of later heats;\n if is_feasible:\n for heat_2 in previous_heats:\n if not self.check_t_tr_fulfilled(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr of last stage is fulfilled for heat_2\n if self.check_change_tau_t_tr_fulfillable(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr is fulfillable on all PREVIOUS stages\n all_t_tr_fulfillable, times_of_heat_stage_copy = \\\n self.change_tau_and_check_all_t_tr_fulfillable(heat_2, 3,\n times_of_heat_stage_copy)\n if all_t_tr_fulfillable == False:\n is_feasible = False\n break\n\n # check (from back to forth), if there are still not-fulfilled t_tr; check, if these t_tr can be fulfilled\n # by changes in start times combined with use of maximum tau\n if is_feasible:\n for heat_2 in reversed(previous_heats):\n if not self.check_t_tr_fulfilled(heat_2, 3, times_of_heat_stage_copy):\n # check, if t_tr of last stage is fulfilled for heat_2\n if self.check_change_t_start_collision_free(heat_2, 3, times_of_heat_stage_copy):\n times_of_heat_stage_copy = self.calc_and_set_t_start_new(heat_2, 3, times_of_heat_stage_copy)\n else:\n is_feasible = False\n break\n\n return is_feasible, t_start_stage_4, times_of_heat_stage_copy\n\n def last_check_stage_4(self, all_heats, times_of_heat_stage_copy):\n # support method for schedule_stage_4;\n # last feasibility check of all heats on stage 3 when scheduling stage 4, to ensure,\n # that changes in processing times don't interfere with starting times on stage 4\n is_feasible = True\n for heat in all_heats:\n if times_of_heat_stage_copy[heat][3][0] + \\\n times_of_heat_stage_copy[heat][3][1] > times_of_heat_stage_copy[heat][4][0]:\n is_feasible = False\n\n return is_feasible\n\n # methods for performance of steps in the state-space, respectively a scheduling step\n\n def step(self, action):\n # perform one step in the state-space, either by moving the next free heat to the next machine\n # or by scheduling the complete last stage; after the step, determine the possible actions, that can be\n # taken from the resulting state without rendering the schedule infeasible; if no action is possible,\n # the next step will lead to the state 'infeasible'\n next_free_heat, stage_3_complete = self.get_next_free_heat()\n next_mach = action\n reward = 0\n is_terminal = False\n is_feasible = 1\n\n if stage_3_complete:\n self.schedule_stage_4(next_mach)\n self.set_vis_state_terminal()\n #self.render('test_render')\n if self.rounds == 3:\n x = 1\n # self.render('test_render') --> only for testing reasons\n is_terminal = True\n reward = self.calc_reward_makespan()\n else:\n self.schedule_one_heat(next_free_heat, next_mach)\n new_next_heat, stage_3_complete = self.get_next_free_heat()\n\n if stage_3_complete:\n self.set_vis_state_stage_four()\n #self.render('test_render') --> only for testing reasons\n self.set_poss_actions_stage_4()\n else:\n self.set_vis_state(new_next_heat)\n #self.render('test_render') --> only for testing reasons\n self.set_poss_actions_stages_1_to_3()\n\n if not self.get_poss_actions():\n self.set_vis_state_infeasible()\n is_feasible = 0\n # self.render('test_render') --> only for testing reasons\n is_terminal = True\n reward = -100\n\n return self.get_vis_state(), is_terminal, reward, is_feasible\n\n def schedule_one_heat(self, heat, next_mach):\n # determine the schedule for the given heat on the given next machine on the next stage\n # used for scheduling of stages 1 to 3\n next_stage = self.get_curr_stage_of_heat(heat) + 1\n self.set_heat_seq_stage_mach(next_stage, next_mach, heat)\n self.add_next_mach_of_heat(heat, next_mach)\n times_of_heat_stage_action = self.copy_times_of_heat_stage_action_complete(next_mach)\n self.set_times_of_heat_stage_complete(times_of_heat_stage_action)\n\n return\n\n def schedule_stage_4(self, next_mach):\n # determine the schedule for the given next machine on stage 4\n times_of_heat_stage_action = self.copy_times_of_heat_stage_action_complete(next_mach)\n self.set_times_of_heat_stage_complete(times_of_heat_stage_action)\n start_times_stage_4 = []\n\n for heat in range(self.get_num_heats()):\n start_times_stage_4.append([heat, self.copy_times_of_heat_stage_complete()[heat][-1][0]])\n self.add_next_mach_of_heat(heat, next_mach)\n\n for heats_and_times in start_times_stage_4:\n self.set_heat_seq_stage_mach(4, next_mach, heats_and_times[0])\n\n return\n\n # methods for calculation of reward\n\n def calc_reward_makespan(self):\n # reward for makespan: basic reward for makespan - actual makespan\n # reward consists of a basic point count, which is reduced with regard to the makespan\n reward_makespan = self.calc_basic_reward_ms() - self.calc_makespan()\n return reward_makespan\n\n def calc_makespan(self):\n # calculate the makespan of a complete schedule\n return max(self.get_t_free_total_stage_mach(4, 0), self.get_t_free_total_stage_mach(4, 1))\n\n def calc_basic_reward_ms(self):\n # calculate basic reward for the makespan\n # calculated as a 'worst case' scenario, in which on each stage all the heats are processed on the same machine\n # and one after another, and in which the processing on the next stage only starts after all heats have been\n # processed on the previous stage\n # it is to be noted, that this scenario usually not happens due to other heuristics and rules within the\n # scheduling process, and therefore it is just a theoretical baseline for the makespan\n\n t_worst_case_stage_1 = max((self.get_tau_low_stage_mach(1, 0) + self.get_t_s_stage_mach(1, 0)\n + self.get_t_cl_stage_mach(1, 0)),\n (self.get_tau_low_stage_mach(1, 1) + self.get_t_s_stage_mach(1, 1)\n + self.get_t_cl_stage_mach(1, 1))) * self.get_num_heats() - 1 \\\n + max(self.get_tau_low_stage_mach(1, 0), self.get_tau_low_stage_mach(1, 1))\n t_worst_case_stage_2 = max((self.get_tau_low_stage_mach(2, 0) + self.get_t_s_stage_mach(2, 0)\n + self.get_t_cl_stage_mach(2, 0)),\n (self.get_tau_low_stage_mach(2, 1) + self.get_t_s_stage_mach(2, 1)\n + self.get_t_cl_stage_mach(2, 1))) * self.get_num_heats() - 1 \\\n + max(self.get_tau_low_stage_mach(2, 0), self.get_tau_low_stage_mach(2, 1))\n t_worst_case_stage_3 = max((self.get_tau_low_stage_mach(3, 0) + self.get_t_s_stage_mach(3, 0)\n + self.get_t_cl_stage_mach(3, 0)),\n (self.get_tau_low_stage_mach(3, 1) + self.get_t_s_stage_mach(3, 1)\n + self.get_t_cl_stage_mach(3, 1))) * self.get_num_heats() - 1 \\\n + max(self.get_tau_low_stage_mach(3, 0), self.get_tau_low_stage_mach(3, 1))\n t_worst_case_stage_4 = max(self.get_tau_low_stage_mach(3, 0), self.get_tau_low_stage_mach(3, 1)) \\\n * self.get_num_heats()\n\n makespan_worst_case = t_worst_case_stage_1 + t_worst_case_stage_2 + t_worst_case_stage_3 + t_worst_case_stage_4\n return makespan_worst_case\n\n # Methods for the saving of the output and the graphical rendering of the schedule\n\n def save_output(self):\n # write output to lists for graphical rendering of the schedule\n machines_stages = [['mach0'], ['mach1', 'mach2'], ['mach3', 'mach4'], ['mach5', 'mach6'], ['mach7', 'mach8']]\n self.heat_seq_out = []\n self.mach_out = []\n self.start_times = []\n self.tau_out = []\n for stage, mach_list in enumerate(self.heat_seq_stage_mach):\n for mach, heat_list in enumerate(mach_list):\n for heat in heat_list:\n if (stage <= len(self.copy_times_of_heat_stage_complete()[heat])):\n self.mach_out.append(machines_stages[stage][mach])\n self.heat_seq_out.append('heat' + str(heat + 1))\n self.start_times.append(self.get_times_of_heat_stage(heat, stage)[0])\n self.tau_out.append(self.get_times_of_heat_stage(heat, stage)[1])\n\n return\n\n def render(self, filename):\n # render the Gantt chart for display of solution\n self.save_output()\n data = {'Heats': self.heat_seq_out, 'Machines': self.mach_out, 'Start_Times': self.start_times,\n 'Processing_Times': self.tau_out}\n\n df_results_heats = pd.DataFrame.from_dict(data)\n\n mach1_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach1']\n mach1_df = mach1_df.set_index('Heats')\n mach1_times = list(zip(round(mach1_df.Start_Times), mach1_df.Processing_Times))\n\n mach2_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach2']\n mach2_df = mach2_df.set_index('Heats')\n mach2_times = list(zip(round(mach2_df.Start_Times), mach2_df.Processing_Times))\n\n mach3_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach3']\n mach3_df = mach3_df.set_index('Heats')\n mach3_times = list(zip(round(mach3_df.Start_Times), mach3_df.Processing_Times))\n\n\n mach4_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach4']\n mach4_df = mach4_df.set_index('Heats')\n mach4_times = list(zip(round(mach4_df.Start_Times), mach4_df.Processing_Times))\n\n\n mach5_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach5']\n mach5_df = mach5_df.set_index('Heats')\n mach5_times = list(zip(round(mach5_df.Start_Times), mach5_df.Processing_Times))\n\n\n mach6_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach6']\n mach6_df = mach6_df.set_index('Heats')\n mach6_times = list(zip(round(mach6_df.Start_Times), mach6_df.Processing_Times))\n\n\n mach7_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach7']\n mach7_df = mach7_df.set_index('Heats')\n mach7_times = list(zip(round(mach7_df.Start_Times), mach7_df.Processing_Times))\n\n\n mach8_df = df_results_heats.loc[df_results_heats['Machines'] == 'mach8']\n mach8_df = mach8_df.set_index('Heats')\n mach8_times = list(zip(round(mach8_df.Start_Times), mach8_df.Processing_Times))\n\n # parameters for plotsize\n x_max = 2 * self.get_num_heats() * (self.get_tau_low_stage_mach(1, 0) +\\\n self.get_tau_low_stage_mach(4,0))\n y_max = 400\n bar_width = 40\n tick_interval = 50\n font_size = 10\n\n # Declaring a figure \"gnt\"\n fig, gnt = plt.subplots(figsize=(9, 7))\n\n # Setting Y-axis limits\n gnt.set_ylim(0, y_max + tick_interval)\n\n # Setting X-axis limits\n gnt.set_xlim(0, x_max)\n\n # Setting labels for x-axis and y-axis\n gnt.set_xlabel('hours since start')\n gnt.set_ylabel('Machines')\n\n # Setting ticks on y-axis\n gnt.set_yticks([tick_interval, 2 * tick_interval, 3 * tick_interval, 4 * tick_interval,\n 5 * tick_interval, 6 * tick_interval, 7 * tick_interval, 8 * tick_interval])\n # Labelling tickes of y-axis\n gnt.set_yticklabels(['CC 1', 'CC 2', 'LF 1', 'LF 2', 'AOD 1',\n 'AOD 2', 'EAF 1', 'EAF 2'])\n\n # Setting graph attribute\n gnt.grid(True)\n\n # Setting the Bars for the heats\n # Bar for EAF 1\n gnt.broken_barh(mach1_times, ((8 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for EAF 2\n gnt.broken_barh(mach2_times, ((7 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for AOD 1\n gnt.broken_barh(mach3_times, ((6 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for AOD 2\n gnt.broken_barh(mach4_times, ((5 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for LF 1\n gnt.broken_barh(mach5_times, ((4 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for LF 2\n gnt.broken_barh(mach6_times, ((3 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for CC 1\n gnt.broken_barh(mach7_times, ((2 * tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Bar for CC 2\n gnt.broken_barh(mach8_times, ((tick_interval - (bar_width / 2)), bar_width), facecolors='tab:orange',\n edgecolors='black')\n\n # Annotate bars with job-names\n\n for heat in mach1_df.index:\n gnt.annotate(heat, (mach1_df.loc[heat].Start_Times + (mach1_df.loc[heat].Processing_Times / 2),\n 8 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach2_df.index:\n gnt.annotate(heat, (mach2_df.loc[heat].Start_Times + (mach2_df.loc[heat].Processing_Times / 2),\n 7 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach3_df.index:\n gnt.annotate(heat, (mach3_df.loc[heat].Start_Times + (mach3_df.loc[heat].Processing_Times / 2),\n 6 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach4_df.index:\n gnt.annotate(heat, (mach4_df.loc[heat].Start_Times + (mach4_df.loc[heat].Processing_Times / 2),\n 5 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach5_df.index:\n gnt.annotate(heat, (mach5_df.loc[heat].Start_Times + (mach5_df.loc[heat].Processing_Times / 2),\n 4 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach6_df.index:\n gnt.annotate(heat, (mach6_df.loc[heat].Start_Times + (mach6_df.loc[heat].Processing_Times / 2),\n 3 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach7_df.index:\n gnt.annotate(heat, (mach7_df.loc[heat].Start_Times + (mach7_df.loc[heat].Processing_Times / 2),\n 2 * tick_interval), ha='center', va='center', size=font_size)\n\n for heat in mach8_df.index:\n gnt.annotate(heat, (mach8_df.loc[heat].Start_Times + (mach8_df.loc[heat].Processing_Times / 2),\n tick_interval), ha='center', va='center', size=font_size)\n\n plt.plot((0, x_max), (2.5 * tick_interval, 2.5 * tick_interval), 'k-')\n plt.plot((0, x_max), (4.5 * tick_interval, 4.5 * tick_interval), 'k-')\n plt.plot((0, x_max), (6.5 * tick_interval, 6.5 * tick_interval), 'k-')\n\n if self.get_vis_state()==[-2, -2]:\n plt.title(\"infeasible schedule\")\n else:\n plt.title(\"feasible schedule round \" + str(self.rounds))\n\n fig.savefig(filename, dpi=None, facecolor='w', edgecolor='w',\n orientation='portrait', format=None,\n transparent=False, bbox_inches=None, pad_inches=0.1, metadata=None)\n plt.show()\n return","sub_path":"scheduling_environment.py","file_name":"scheduling_environment.py","file_ext":"py","file_size_in_byte":51039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"471372216","text":"#balanced tree\n#for each node in tree, height difference between right and left subtrees is at most one\n#takes in root and checks whether tree is balanced\n\n\nclass Node():\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\n#same as \"get_height\", but if unbalanced, return -1\n\ndef is_balanced(root):\n #returns height of tree, and -1 if unbalanced\n #base case 1\n if root is None:\n return 0\n #base case 2, not necessary\n if root.left is None and root.right is None:\n return 1\n else:\n left = is_balanced(root.left)\n right = is_balanced(root.right)\n #if either left or right is not balanced, then return not balanced\n if left == -1 or right == -1:\n return -1\n #return difference\n if abs(left - right) > 1:\n return -1\n #return height\n else:\n return 1 + max(left, right)\n\ndef get_height(root):\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return 1\n else:\n left = get_height(root.left)\n right = get_height(root.right)\n if left==-1 or right==-1:\n return -1\n if abs(left - right) > 1:\n return -1\n else:\n return 1 + max(left, right)\n\n\n\n#recursive solution, as each subtree must also be balanced.\n#base case\n#leaf node on left or right\n#could return height and compare\n\na = Node(314)\nb = Node(6)\nc = Node(271)\nd = Node(28)\ne = Node(0)\nf = Node(561)\ng = Node(3)\nh = Node(17)\ni = Node(6)\nj = Node(2)\nk = Node(1)\nl = Node(401)\nm = Node(641)\nn = Node(257)\no = Node(271)\np = Node(28)\n\na.left = b\nb.left = c\nc.left = d\nc.right = e\nb.right = f\nf.right = g\ng.left = h\na.right = i\ni.right = o\no.right = p\ni.left = j\nj.right = k\nk.left = l\nl.right = m\nk.right = n\n\nprint(is_balanced(a))\nprint(is_balanced(c))\nprint(is_balanced(k))","sub_path":"elements/binary_trees/treebalanced.py","file_name":"treebalanced.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"554909543","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom pysc2.agents import base_agent\nfrom pysc2.lib import actions, features, units\n\nfrom enum import IntEnum, auto, Enum\nimport random\n\nimport heapq\nimport unit_build_time\nimport data_IO\n\nEnableDebug = False\n\nclass AutoNumber(Enum):\n def __new__(cls):\n value = len(cls.__members__) # note no + 1\n obj = object.__new__(cls)\n obj._value_ = value\n return obj\n\n def __int__(self):\n return self.value\n\n\n\nclass MacroGlobalFeatureSet(AutoNumber):\n MineralCount = ()\n GasCount = ()\n Population = ()\n PopulationCap = () # essentially same infomation as overlord count\n FreeSupply = () # populationCap - population\n WorkerCount = ()\n ArmyCount = ()\n WorkerIdle = ()\n LarvaCount = ()\n\n WorkerBuilding = ()\n PopulationBuilding = ()\n\n #QueenCount = ()\n #BaseCount = ()\n\n #ExtractorCount = ()\n #WorkerOnMineral = ()\n #WorkerOnGas = ()\n\n FeatureDimension = ()\n\nclass MacroPerBaseFeatureSet(AutoNumber):\n IsMain = ()\n MineralFieldCount = ()\n WorkerOnMineral = ()\n\n GasCount = ()\n WorkerOnGas = ()\n\n WorkerBuilding = ()\n\n QueenCount = ()\n IsInjected = ()\n\n FeatureDimension = ()\n\nclass MacroRewardRecord(AutoNumber):\n MineralCount = ()\n FeatureDimension = ()\n\nclass ActionRecord(AutoNumber):\n # record all actions\n # note it does not record all effective action, which is recorded separately\n BuildWorker = ()\n BuildOverloard = ()\n FeatureDimension = ()\n\nUnitBuildingMap = {\n units.Zerg.Drone : MacroGlobalFeatureSet.WorkerBuilding,\n units.Zerg.Overlord : MacroGlobalFeatureSet.PopulationBuilding\n}\n\nclass ZergMacroAgent(base_agent.BaseAgent):\n def __init__(self, MaxStep):\n super(ZergMacroAgent, self).__init__()\n self.pauseDebug = \"0\"\n\n self.maxStep = MaxStep\n self.reset()\n \n def reset(self):\n super(ZergMacroAgent, self).reset()\n self.mineral = 0\n self.reward = 0\n\n self.startX = 0\n self.startY = 0\n\n self.internalStepCounter = 0\n\n self.globalActionQueue = []\n self.buildHeapq = []\n\n self.globalFeatureRecord = []\n self.globalRewardRecord = []\n self.ActionRecord = []\n self.EffectiveRecord = []\n\n self.performedLastOperation = False\n\n return\n\n def can_do(self, obs, action):\n return action in obs.observation.available_actions\n\n def get_units_by_type(self, obs, unit_type):\n return [unit for unit in obs.observation.feature_units\n if unit.unit_type == unit_type]\n\n def moveDroneToMineral(self, obs):\n if(obs.observation.player.idle_worker_count >= 1):\n minerals = self.get_units_by_type(obs, units.Neutral.MineralField)\n if(len(minerals) > 0):\n actionUnit = []\n actionUnit.append((actions.FUNCTIONS.select_idle_worker(),actions.FUNCTIONS.select_idle_worker.id))\n\n mineral = random.choice(minerals)\n actionUnit.append((actions.FUNCTIONS.Harvest_Gather_screen(\"now\", (mineral.x, mineral.y)),actions.FUNCTIONS.Harvest_Gather_screen.id))\n\n self.globalActionQueue.append(actionUnit)\n return True\n\n return False\n\n def buildDroneAction(self, obs):\n larvae = self.get_units_by_type(obs, units.Zerg.Larva)\n if len(larvae) > 0:\n larva = random.choice(larvae)\n\n actionUnit = []\n actionUnit.append((actions.FUNCTIONS.select_point(\"select_all_type\", (larva.x,\n larva.y)), actions.FUNCTIONS.select_point.id))\n\n actionUnit.append((actions.FUNCTIONS.Train_Drone_quick(\"now\"), actions.FUNCTIONS.Train_Drone_quick.id))\n \n self.globalActionQueue.append(actionUnit)\n return True\n\n return False\n\n def buildOverlordAction(self, obs):\n larvae = self.get_units_by_type(obs, units.Zerg.Larva)\n if len(larvae) > 0:\n larva = random.choice(larvae)\n\n actionUnit = []\n actionUnit.append((actions.FUNCTIONS.select_point(\"select_all_type\", (larva.x,\n larva.y)), actions.FUNCTIONS.select_point.id))\n\n actionUnit.append((actions.FUNCTIONS.Train_Overlord_quick(\"now\"), actions.FUNCTIONS.Train_Overlord_quick.id))\n \n self.globalActionQueue.append(actionUnit)\n return True\n\n return False\n\n def isSameActionUnit(self, actionUnit1, actionUnit2):\n if(len(actionUnit1) != len(actionUnit2)):\n return False\n\n actionUnitLen = len(actionUnit1)\n for i in range(actionUnitLen):\n action1 = actionUnit1[i]\n action2 = actionUnit2[i]\n\n if(action1[1] != action2[1]):\n # Qustion: shall we check not just function id?\n return False\n\n return True\n\n def dedupConsecutiveSameOrder(self):\n if(len(self.globalActionQueue)>2):\n i = 0\n while(i in range(len(self.globalActionQueue) - 1)):\n curActionUnit = self.globalActionQueue[i]\n nextActionUnit = self.globalActionQueue[i+1]\n\n if(self.isSameActionUnit(curActionUnit, nextActionUnit)):\n del self.globalActionQueue[i]\n else:\n i+=1\n\n return self.globalActionQueue\n\n def executeDequeue(self, obs):\n if(len(self.globalActionQueue)>0):\n actionUnit = self.globalActionQueue.pop(0)\n\n if(len(actionUnit) == 0):\n return actions.FUNCTIONS.no_op(), actions.FUNCTIONS.no_op.id\n else:\n firstActionPair = actionUnit.pop(0)\n actionFunc = firstActionPair[0]\n actionFuncId = firstActionPair[1]\n\n if self.can_do(obs, actionFuncId):\n if(len(actionUnit) > 0):\n self.globalActionQueue = [actionUnit] + self.globalActionQueue\n\n # if it is a build action, register it in build queue\n if actionFuncId in unit_build_time.UnitBuildActionSet:\n unitId = unit_build_time.UnitBuildAction[actionFuncId]\n unitBuildTimeStep = unit_build_time.UnitBuildTime[unitId]\n expectFinishTime = self.internalStepCounter + unitBuildTimeStep\n heapq.heappush(self.buildHeapq, (expectFinishTime, unitId))\n\n return actionFunc, actionFuncId\n\n return actions.FUNCTIONS.no_op(), actions.FUNCTIONS.no_op.id\n\n # TODO: port in online learning\n def trainModel(self, buffer):\n return True\n\n def initStep(self, obs):\n player_y, player_x = (obs.observation.feature_minimap.player_relative ==\n features.PlayerRelative.SELF).nonzero()\n self.startX = player_x.mean()\n self.startY = player_y.mean()\n\n self.reset()\n return\n\n def lastStep(self,obs):\n print('Final Mineral:', str(self.mineral))\n print('Final Step:', str(self.internalStepCounter))\n \n gf_path, _ = data_IO.genLatestFile(\".//data\", \"globalFeatures\")\n data_IO.export2DArray(self.globalFeatureRecord, gf_path)\n\n rw_path, _ = data_IO.genLatestFile(\".//data\", \"macroRewards\")\n data_IO.export2DArray(self.globalRewardRecord, rw_path)\n\n action_path, _ = data_IO.genLatestFile(\".//data\", \"actions\")\n data_IO.export2DArray(self.ActionRecord, action_path)\n\n effectiveAction_path, _ = data_IO.genLatestFile(\".//data\", \"effectiveAction\")\n data_IO.export2DArray(self.EffectiveRecord, effectiveAction_path)\n\n self.performedLastOperation = True\n \n return\n\n def step(self, obs):\n super(ZergMacroAgent, self).step(obs)\n\n if EnableDebug and (self.pauseDebug == \"1\" or self.internalStepCounter % 100 == 0):\n self.pauseDebug = input(\"pause prompt \\n\")\n print('current Step:', str(self.internalStepCounter))\n print('Units In Queue', str(len(self.buildHeapq)))\n\n if obs.first():\n self.initStep(obs)\n\n self.internalStepCounter += 1\n self.expireBuiltUnitFromQueue()\n \n globalFeatures = self.globalMacroFeatureExtractor(obs)\n rewards = self.MacroRewardExtractor(obs)\n \n self.globalFeatureRecord.append(globalFeatures)\n self.globalRewardRecord.append(rewards)\n \n # ------- Detect last iteration -----------\n if obs.last() or (self.internalStepCounter >= self.maxStep - 4 and self.maxStep > 0):\n # capture 1 second before the end\n if not self.performedLastOperation:\n self.lastStep(obs)\n\n # ------------------------------------------\n\n # ------- Core sub-Models -----------------------------\n actionVector = [0] * int(ActionRecord.FeatureDimension)\n\n if(globalFeatures[int(MacroGlobalFeatureSet.FreeSupply)] <= 1): \n self.buildOverlordAction(obs)\n actionVector[int(ActionRecord.BuildOverloard)] = 1\n else:\n self.buildDroneAction(obs)\n actionVector[int(ActionRecord.BuildWorker)] = 1\n\n self.ActionRecord.append(actionVector)\n # -----------------------------------------------------\n # heuristic filters\n self.dedupConsecutiveSameOrder()\n\n # ------- Core final ranker ----------------------------\n\n\n actionFunc, actionFuncId = self.executeDequeue(obs) \n self.EffectiveRecord.append(actionFuncId)\n return actionFunc\n\n\n def MacroRewardExtractor(self,obs):\n f = [0]*int(MacroRewardRecord.FeatureDimension)\n f[int(MacroRewardRecord.MineralCount)] = obs.observation.player.minerals\n\n return f\n\n def globalMacroFeatureExtractor(self, obs):\n f = [0]*int(MacroGlobalFeatureSet.FeatureDimension)\n\n self.mineral = obs.observation.player.minerals\n\n f[int(MacroGlobalFeatureSet.MineralCount)] = obs.observation.player.minerals\n f[int(MacroGlobalFeatureSet.GasCount)] = obs.observation.player.vespene\n\n f[int(MacroGlobalFeatureSet.Population)] = obs.observation.player.food_used\n f[int(MacroGlobalFeatureSet.PopulationCap)] = obs.observation.player.food_cap\n f[int(MacroGlobalFeatureSet.FreeSupply)] = (obs.observation.player.food_cap - obs.observation.player.food_used)\n\n f[int(MacroGlobalFeatureSet.WorkerCount)] = obs.observation.player.food_workers\n f[int(MacroGlobalFeatureSet.WorkerIdle)] = obs.observation.player.idle_worker_count\n f[int(MacroGlobalFeatureSet.ArmyCount)] = obs.observation.player.army_count\n\n f[int(MacroGlobalFeatureSet.LarvaCount)] = obs.observation.player.larva_count\n #f[int(MacroGlobalFeatureSet.BaseCount)] = len(self.get_units_by_type(obs, units.Zerg.Hatchery))\n\n self.extractUnitInBuild(f)\n return f\n\n def extractUnitInBuild(self, f):\n if len(self.buildHeapq) == 0:\n return\n\n for i in range(len(self.buildHeapq)):\n unitInBuildId = self.buildHeapq[i][1]\n\n # simulated switch statement\n # TODO: more optimized lookup out of stack\n featureId = int(UnitBuildingMap.get(unitInBuildId, -1))\n\n if featureId != -1:\n f[featureId] += 1\n\n return\n\n def expireBuiltUnitFromQueue(self):\n if len(self.buildHeapq) == 0:\n return\n\n finishTimeStep, unitId = heapq.heappop(self.buildHeapq)\n\n while finishTimeStep <= self.internalStepCounter:\n if(len(self.buildHeapq) == 0):\n return\n finishTimeStep, unitId = heapq.heappop(self.buildHeapq)\n\n if finishTimeStep > self.internalStepCounter:\n heapq.heappush(self.buildHeapq, (finishTimeStep, unitId))\n\n return\n\n ","sub_path":"zerg_macro.py","file_name":"zerg_macro.py","file_ext":"py","file_size_in_byte":10946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"9435780","text":"\"\"\"\nhttps://codeforces.com/problemset/problem/727/D\n\nD. T-shirts Distribution\n\nThe organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.\n\nDuring the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.\n\nWrite a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:\n\nthe size he wanted, if he specified one size;\nany of the two neibouring sizes, if he specified two sizes.\nIf it is possible, the program should find any valid distribution of the t-shirts.\n\nInput\nThe first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000.\n\nThe second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants.\n\nThe following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.\n\nOutput\nIf it is not possible to present a t-shirt to each participant, print «NO» (without quotes).\n\nOtherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input.\n\nIf there are multiple solutions, print any of them.\n\nExamples\n\n0 1 0 1 1 0\n3\nXL\nS,M\nXL,XXL\n\nYES\nXL\nM\nXXL\n\n1 1 2 0 1 1\n5\nS\nM\nS,M\nXXL,XXXL\nXL,XXL\n\nNO\n\n1. s node: 6 edges -> sizes, where capacity is quantity of each size\n2. S M L XL XXL XXL -> candidates matched by preference, capacity = 1\n3. candidates -> t node\n\"\"\"\n\nfrom algorithms.graph_weighted import WeightedGraph\nfrom collections import defaultdict, deque\n\n# S, M, L, XL, XXL, XXXL = map(int, input().strip().split())\nsizes = deque(list(map(int, input().strip().split())))\nN = int(input())\n\nmapping = {'S': 1, 'M': 2, 'L': 3, 'XL': 4, 'XXL': 5, 'XXXL': 6,\n 1: 'S', 2: 'M', 3: 'L', 4: 'XL', 5: 'XXL', 6: 'XXXL'}\n\nsize = len(sizes) + N + 2\ngraph = [[0] * size for _ in range(size)]\n\nfor person in range(7, 7 + N):\n for size in input().strip().split(','):\n size = mapping[size]\n graph[size][person] += 1\n graph[person][-1] = 1\n\nsizes.appendleft(0)\nfor i in range(N + 1):\n sizes.append(0)\n\ngraph[0] = list(sizes)\n\nfor row in graph:\n print(row)\n\ng = WeightedGraph(graph, directed=True)\nsource = 0\nsink = len(graph) - 1\n\nmaxflow = g.ford_fulkerson(source, sink)\n\nif maxflow == N:\n print('YES')\n\n for person in range(7, 7 + N):\n print(mapping[graph[person].index(1)])\nelse:\n print('NO')\n\nprint('residual graph')\nfor row in graph:\n print(row)\n","sub_path":"code_forces/727_D_tshirts_distribution.py","file_name":"727_D_tshirts_distribution.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"57420554","text":"#----1---+----2----+----3----+----4----+----5----+----6----+----7----+----8----+\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# データの読み込み\ndata = pd.read_csv(\"sensor_data_200.txt\", delimiter = \" \", \n header = None, names = (\"date\", \"time\", \"ir\", \"lidar\"))\n\n# 各センサ値の頻度を集計\nfreqs = pd.DataFrame(data[\"lidar\"].value_counts())\n# freqsに確率の列を追加\nfreqs[\"probs\"] = freqs[\"lidar\"]/len(data[\"lidar\"])\n\n# LiDARのセンサ値のヒストグラムの作成\nfreqs[\"probs\"].sort_index().plot.bar()\nplt.show()","sub_path":"Chap02/224.py","file_name":"224.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"148487202","text":"from ggame import App, Color, LineStyle, Sprite, CircleAsset, Frame, RectangleAsset, TextAsset\nfrom math import floor, sin, cos\n\n#-----------------------------------------------------\nred = Color(0xff0000, 1.0)\nblue = Color(0x0000ff, 1.0)\nblack = Color(0x000000, 1.0)\ngreen = Color(0x0fff6f, 1.0)\nwhite = Color(0xffffff, 1.0)\nclear = Color(0xffffff, 0.0)\n#-----------------------------------------------------\nframeWidth = 800\nframeHeight = 800\n#-----------------------------------------------------\nnoLine = LineStyle(0, black)\noutline = LineStyle(1,black)\n#-----------------------------------------------------\ndef funcInterpreter(depVar, indepVar, equation,t):\n if equation.count(\"(\") != equation.count(\")\") or equation.count(\"=\") != 1:\n print(\"Invalid input given\")\n else:\n newEquation = \"\"\n for i in equation:\n if i != \" \":\n newEquation += i\n #print(\"Interpreting:\", newEquation)\n if newEquation.find(\"=\") != 1 or newEquation[newEquation.find(\"=\")+1:len(newEquation)].find(depVar) != -1:\n print(\"Implementation of implicits needed\")\n print(depVarSolver(depVar, indepVar, newEquation))\n pluggableEquation = depVarSolver(depVar, indepVar, newEquation)\n else:\n equationR = newEquation[newEquation.find(\"=\")+1: len(newEquation)]\n # print(\"equationR\", equationR)\n letterOperands = \"sincotaelg\"\n status = 0\n for i in letterOperands:\n if equationR.find(i) != -1:\n status += 1\n if equationR.count(indepVar) > 0 and indepVar != \"nil\":\n pluggableEquation = pluggerSetup(depVar, indepVar, equationR)\n # print(\"pluggable:\", pluggableEquation)\n else:\n b = getOperandsAndTerms(equationR)\n pluggableEquation = prenEliminator(b[0],b[1])\n points = []\n #for i in range(1,10):\n # points.append((funcPlugger(depVar, indepVar, str(pluggableEquation), i)))\n #print(pluggableEquation)\n points.append((funcPlugger(depVar, indepVar, str(pluggableEquation), t)))\n #points = \"nil\" \n return(points)\n \ndef depVarSolver(depVar, indepVar, equation):\n print(\"Implicit function entered, Isolating dependent variable\")\n if equation.find(\"=\")!= 1:\n equationL = equation[0:equation.find(\"=\")-1]\n equationL = expressionSplitter(equationL)\n else:\n equationL = [equation[0]]\n equationR = equation[equation.find(\"=\")+1: len(equation)]\n equationR = expressionSplitter(\"y\", equationR)\n #newEquation = equationL +\"=\"+equationR\n return(equationL, \"=\", equationR)\n \ndef expressionSplitter(depVar, expression):\n if expression.find(depVar) == -1:\n print(\"DepVar not found\", expression)\n return([expression])\n else:\n terms = []\n term = \"\"\n p = 0\n for i in expression:\n term += i\n if i == \"(\":\n p += 1\n elif i == \")\":\n p -= 1\n if i == \"+\" and p == 0:\n terms.append(term[0:len(term)-1])\n term = \"+\"\n if term != \"\":\n terms.append(term)\n print(\"DeVars found\", terms)\n return(terms)\n \ndef funcCombiner(equation):\n #print(equation)\n equationL = getOperandsAndTerms(equation[0:equation.find(\"=\")])\n #print(equationL)\n equationR = getOperandsAndTerms(equation[equation.find(\"=\"):len(equation)-1])\n #print(equationR)\n equationLOperators=[]\n for i in equationL[1]:\n if i == \"-\":\n equationLOperators.append(\"+\")\n elif i == \"+\":\n equationLOperators.append(\"-\")\n else:\n equationLOperators.append(i)\n return(equationR[0] + equationL[0],equationR[1] + equationLOperators[:])\n \ndef funcCompiler(terms, operands):\n output = \"\"\n for i in range(0, len(terms)):\n output += terms[i]\n if i < len(terms) - 1:\n output += operands[i]\n return(output)\n\ndef prenEliminator(terms, operands):\n newTerms = []\n operators = []\n for z in terms:\n newTerms.append(z)\n for z in operands:\n operators.append(z)\n pp = 1 #Status of parenthesis being present\n g = 0 #Just a method to stop infinite loops if there is an error in my code\n \n while pp == 1 and g != 20:\n #print(\"while\", newTerms, \"g=\", g)\n #print(\"pren:\", newTerms)\n #print(\"pren:\", operands)\n g += 1\n pcheck = \"\"\n letterOperands = \"sincotaelg\"\n status = 0\n for i in range(0,len(newTerms)):\n status = 0\n for k in letterOperands:\n if newTerms[i].find(k) != -1:\n status += 1\n if status != 0:\n newTerms[i] = str(funcSolver(getOperandsAndTerms(newTerms[i])[0],getOperandsAndTerms(newTerms[i])[1]))\n if status == 0:\n for i in range(0,len(newTerms)):\n if str(newTerms[i]).isdigit() == False:\n #print(\"Non-int detected in prenElim\")\n p = str(newTerms[i]).count(\"(\")\n term = \"\"\n newTerm = \"\"\n outside = \"\"\n for k in range(len(newTerms[i])):\n currentTerm = (newTerms[i])[k]\n term += currentTerm\n if currentTerm == \"(\":\n #print(\"Hey we found an opening parenthesis!\", newTerms, k)\n outside += term[0:len(term)-1:]\n #print(\"This is the outside:\", outside)\n if len(outside) > 0:\n #print(\"The outside is longer than 0\")\n if outside[len(outside) - 1] == \")\" or outside[len(outside) - 1].isdigit() == True or outside[len(outside) - 1] == \"x\" or outside[len(outside) - 1] == \"y\":\n #print(\"We decided to add a multiplier\")\n outside += \"*\"\n term = \"(\"\n elif currentTerm == \")\" and term[0] == \"(\" and len(term[1:len(term)-1:]) > 0:\n term = term[1:len(term)-1:]\n newTerm = str(funcSolver(getOperandsAndTerms(term)[0],getOperandsAndTerms(term)[1]))\n outside += \"{0}\"\n term = \"\"\n outside = outside.format(newTerm)\n elif currentTerm == \")\" and term[0] == \"(\" and len(term[1:len(term)-1:]) == 0:\n #print(\"There is an empty term; Substituting 0\")\n term = \"\"\n outside += \"0\"\n if len(term) > 0 and len(outside) > 0:\n if outside[len(outside) - 1].isdigit() == True and term[0].isdigit == True:\n term = \"*\" + term\n outside += term\n #print(\"cash me\", outside, term)\n else:\n outside += term\n\n newTerms[i] = str(outside)\n ##print(\"newTerms[i]\", newTerms[i])\n for h in newTerms:\n pcheck += str(h)\n if pcheck.count(\"(\") == 0:\n pp = 0\n \n if len(newTerms) > 1:\n #print(\"Int Solver\", newTerms)\n newTerms = funcSolver(newTerms, operands)\n return(newTerms)\n else:\n output = \"\"\n for i in newTerms:\n output += i\n output = float(output)\n return(output) \n\ndef getOperandsAndTerms(equation):\n #initial Seperation\n terms = []\n term = \"\"\n operands = []\n letterOperands = \"sincotaelg\" #Letters in complex operands like trig and log functions\n p = 0\n op = 1\n for i in str(equation):\n status = 0\n for letterOp in letterOperands:\n if i == letterOp:\n status = 1\n if i != \" \" and i != \"'\" and i != \"[\" and i != \"]\":\n if i == \"(\" or i == \"{\":\n p += 1\n if term != \"\" and term.count(\"(\") == 0:\n if letterOperands.find(term[len(term)-1]) == -1:\n terms.append(term)\n term = \"\"\n op = 0\n if op == 0 and p == 1:\n if len(term) > 0:\n if letterOperands.find(term[len(term)-1]) == -1:\n operands.append(\"*\")\n #print(\"OP == 0\", term, terms, operands)\n else:\n operands.append(\"*\")\n elif i == \")\" or i == \"}\":\n p -= 1\n if p == 0 and i != \")\" and i != \"}\":\n if i == \"+\" or i == \"*\" or i == \"/\" or i == \"^\":\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif i == \"-\":\n if op == 1:\n op = 2\n term += i\n elif op == 2:\n op = 0\n term = term[0:len(term)-1]\n else:\n #minusOperator\n operands.append(i)\n op = 1\n if term != \"\":\n terms.append(term)\n term = \"\"\n elif i.isdigit() == True or i == \".\" or status == 1:\n if status == 1 and len(term) > 0:\n if term[0].isdigit():\n terms.append(term)\n term = i\n operands.append(\"*\")\n else:\n term += i\n else:\n term += i\n op = 0\n elif i.isdigit() == False:\n if term != \"\":\n terms.append(term)\n term = \"\"\n op = 0\n terms.append(i)\n if len(terms) > len(operands) + 1:\n operands.append(\"*\")\n op = 1\n elif p == 0 and (i == \")\" or i == \"}\"):\n term += i\n terms.append(term)\n term = \"\"\n op = 0\n else:\n term += i\n if term != \"\":\n terms.append(term)\n #print(\"GottenTerms\", terms, \"GottenOperands\", operands, \"from\", equation)\n for i in range(0,len(terms)):\n #print(terms[i])\n if terms[i] == \"-\":\n terms[i] = \"-1\"\n return((terms,operands))\n \ndef funcSolver(terms, operands):\n letterOperands = \"sincotaelg\"\n #print(\"funcSolverCalled\")\n #print(\"terms:\", terms)\n #print(\"operands:\", operands)\n newTerms = []\n for i in terms:\n status = 0\n for letter in letterOperands:\n if i.find(letter) != -1:\n status = 1\n if status == 1:\n if i.find(\"(\") != -1:\n term = \"\"\n for k in i:\n if i != \"(\" and i != \")\":\n term += k\n inside = i[i.find(\"(\")+1:i.find(\")\")]\n term = i[0:i.find(\"(\")]\n else:\n term = i\n inside = \"\"\n status = 0 \n for k in term:\n if k.isdigit() and status == 0:\n #THIS NEEDS TO CHANGE FOR NESTED COMPLEX OPERANDS\n inside += k\n else:\n status += 1\n if status == 1:\n term = term[0:term.find(i)-1]\n #print(i, \"term\", term, \"inside\", inside)\n if term[0:3] == \"log\":\n #print(\"INSIDE\", inside)\n expression = \"\"\n logBase = 0\n if inside.find(\",\") != -1:\n expression = inside[0:inside.find(\",\")]\n logBase = inside[inside.find(\",\")+1:len(inside)]\n #print(logBase)\n if len(expression) > 1:\n expression = str(prenEliminator(getOperandsAndTerms(expression)[0],getOperandsAndTerms(expression)[1]))\n newTerms.append(log(float(expression))/log(float(logBase)))\n else:\n if len(inside) > 1:\n inside = prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1])\n newTerms.append(round(log(float(inside))/log(10),5))\n #print(\"logBase\", logBase, \"expression\", expression)\n\n #print(\"Term\", term, float(term[3:len(term)]), log(float(term[3:len(term)])))\n #newTerms.append(log(float(term[3:len(term)])))\n \n else:\n #print(term, \"NOT LOG\")\n if len(inside) > 0:\n term = term + str(prenEliminator(getOperandsAndTerms(inside)[0],getOperandsAndTerms(inside)[1]))\n #print(term)\n #print(i[0:3], term[0:3])\n if term[0:3] == \"sin\":\n newTerms.append(round(sin(float(term[3:len(term)])),5))\n elif term[0:3] == \"cos\":\n newTerms.append(round(cos(float(term[3:len(term)])),5))\n elif term[0:3] == \"tan\":\n newTerms.append(round(tan(float(term[3:len(term)])),5))\n elif term[0:3] == \"sec\":\n newTerms.append(round(1/cos(float(term[3:len(term)])),5))\n elif term[0:3] == \"csc\":\n newTerms.append(round(1/sin(float(term[3:len(term)])),5))\n elif term[0:3] == \"cot\":\n newTerms.append(round(1/tan(float(term[3:len(term)])),5))\n else:\n newTerms.append(i)\n #print(\"The equation you entered was weird. Maybe you should check it.\")\n else:\n newTerms.append(i)\n terms = newTerms\n final = 0\n holder = \"\"\n found = 0\n if len(operands) > 0:\n for i in range(0,len(operands)):\n i = i - found\n if operands[i] == \"^\":\n #print(\"ExpoFound\")\n newTerms[i] = float(terms[i])**float(terms[i+1])\n #print(\"NewTermsAdded\", terms[i], terms[i+1], newTerms[i], \"n\")\n del newTerms[i+1]\n del operands[i]\n found += 1\n #print(\"done\")\n #print(\"expo:\", newTerms, operands)\n found = 0\n for i in range(0,len(operands)):\n #print(found, terms, newTerms, operands)\n i = i - found\n #print(i,len(terms),len(operands))\n #print(terms,operands)\n if operands[i] == \"*\":\n newTerms[i] = float(terms[i])*float(terms[i+1])\n del newTerms[i+1]\n del operands[i]\n found += 1\n elif operands[i] == \"/\":\n newTerms[i] = float(terms[i])/float(terms[i+1])\n del newTerms[i+1]\n del operands[i]\n found += 1\n #print(\"mult:\", newTerms)\n for i in range(0,len(operands)):\n if operands[i] == \"-\":\n newTerms[i+1] = str((-1)*float(terms[i+1]))\n #print(\"sub:\", newTerms)\n for i in newTerms:\n final += float(i)\n else:\n final = \"\"\n for i in str(terms):\n for k in i:\n if k.isdigit() == True or k == \".\" or k == \"-\":\n final += str(k)\n #print(\"FINAL:\",final)\n final = float(final)\n ##print(\"solved:\", final)\n return(final)\n\ndef funcPlugger(depVar, indepVar, equation, t):\n if equation.find(\"=\") != -1:\n equation = equation[equation.find(\"=\")+1:len(equation)]\n a = getOperandsAndTerms(equation.format(t))\n b = prenEliminator(a[0],a[1])\n c = 0\n #print(\"Wubbo\", equation.format(t),a,b)\n if isinstance(b, (list,)):\n #print(b)\n for i in b:\n c += float(i)\n else:\n c = b\n if depVar == \"x\":\n return(c,t)\n else:\n return(t,c)\n \ndef pluggerSetup(depVar, indepVar, equation):\n output = \"\"\n #print(\"PluggerSetup\", depVar, indepVar, equation)\n for i in equation:\n #print(\"plug?\", i, i == indepVar)\n if i == indepVar:\n if len(output)>0:\n if output[len(output)-1].isdigit():\n output += \"*\"+\"{0}\"\n elif output[len(output)-1] == \"-\":\n output += \"1\" + \"*\" + \"{0}\"\n else:\n output += \"{0}\"\n else:\n output += \"{0}\"\n \n elif len(output)>0: \n if output[len(output)-1] == \"}\" and (i.isdigit() or i == \"(\" or i == \"{\"):\n output += \"*\"+i\n else:\n output += i\n else:\n output += i\n #print(output)\n return output\n\ndef getX(xValue):\n x = xValue + float(frameWidth) / 2.0 + 60 - 11\n return(x)\n \ndef getY(yValue):\n y = float(frameHeight) / 2.0 - yValue\n return(y)\n\n#----------------------------------------------------- \ndef color(red, green, blue, alpha):\n letters = {10:\"A\",11:\"B\",12:\"C\",13:\"D\",14:\"E\",15:\"F\"}\n output = \"0x\"\n for i in (int(red), int(green), int(blue)):\n a = int(floor(i / 16))\n if a >= 10:\n output += str(letters[a])\n else:\n output += str(a)\n if i - a*16 >= 10:\n output += str(letters[i - a*16])\n else:\n output += str(i - a*16)\n \n output = int(output, base = 16)\n return (Color(output, alpha))\ndef colorRandom(funcIndex):\n return color(abs(255*sin(0.89*funcIndex+2.3)),abs(255*sin(0.44*funcIndex+1.5)),abs(255*sin(0.25*funcIndex+0.75)), 1.0)\n#-----------------------------------------------------\nclass point(Sprite):\n pt = CircleAsset(5, outline, red)\n def __init__(self, position, color, equation, depVar):\n self.vy = 0\n self.vx = 0\n #print(funcInterpreter(\"y\", \"x\", equation, 0.1))\n self.equation = equation\n self.depVar = depVar\n super().__init__(point.pt, position)\n\nclass drawnPoint(Sprite):\n def func(position, color):\n radius = 3\n pt = CircleAsset(radius, noLine, color)\n newPos = (position[0], position[1]-float(radius)/2.0)\n Sprite(pt, newPos)\n def deriv(position, color):\n radius = 3\n dr = CircleAsset(radius/2, LineStyle(1, color), white)\n newPos = (position[0], position[1]-float(radius)/2.0)\n Sprite(dr,newPos)\n#-----------------------------------------------------\nclass Grapher(App):\n def __init__(self, width, height):\n super().__init__(width, height)\n Grapher.listenMouseEvent(\"click\", self.mouseClick)\n Grapher.listenKeyEvent(\"keydown\",\"space\", self.spacePressed)\n quadrant = RectangleAsset(float(frameWidth-100)/2-1, float(frameHeight)/2-1, outline, clear)\n grid = RectangleAsset((frameWidth-100)/20,40, outline, white)\n for i in range(int((frameWidth-100)/20)):\n for k in range(int(frameHeight/40)):\n Sprite(grid, (i*((frameWidth-100)/20)+100,k*40))\n self.going = False\n self.doFuncs()\n Sprite(RectangleAsset(100,frameHeight, outline, color(215,215,215, 1)), (0,0))\n Sprite(quadrant, (100,0))\n Sprite(quadrant, (float(frameWidth-100)/2+100,0))\n Sprite(quadrant, (100,float(frameHeight)/2))\n Sprite(quadrant, (float(frameWidth-100)/2+100,float(frameHeight)/2))\n #EquationBoxes\n for i in range(20):\n #drawnPoint.func((10,i*40+10), colorRandom(i))\n Sprite(RectangleAsset(99,frameHeight/20,outline,colorRandom(i+1)),(0,i*frameHeight/20))\n \n def mouseClick(self,event):\n operation = input(\"F = finished, D = delete, A = Add, R = Reset\")\n while operation.lower() != \"f\":\n if operation.lower() == \"a\":\n if self.going == False:\n equation = input(\"Equation\")\n indepVar = input(\"IndepVar\")\n self.functions.append((equation, indepVar))\n try:\n b = funcInterpreter(\"y\",\"x\", equation, self.initial)[0]\n except:\n print(\"func failed\")\n try:\n b = funcInterpreter(\"y\",\"x\", equation, self.initial + self.increase / 2)[0]\n except:\n print(\"Function Failed, Going to (0,0)\", equation)\n b = (0,0)\n point((getX(b[0]),getY(b[1])), colorRandom(len(self.functions)), equation, indepVar)\n #Sprite(TextAsset(equation, width=100, align='center',style='12px Arial', fill=black),(5,(len(self.functions)-1)*frameHeight/20+2))\n print(self.functions)\n print(self.functions)\n elif operation.lower() == \"d\":\n index = input(\"Which function do you want to delete? (All or index number)\")\n if index.lower() == \"all\":\n for sprite in self.getSpritesbyClass(point):\n del sprite\n self.functions = []\n elif index.lower().isdigit() and int(index)-1 <= len(self.functions):\n found = 0\n for sprite in self.getSpritesbyClass(point):\n if sprite.equation == functions[index] and found == 0: \n del sprite\n del functions[index]\n found += 1\n else:\n print(\"Please use valid inputs\")\n elif operation.lower() == \"r\":\n self.doFuncs()\n operation = input(\"F = finished, D = delete, A = Add, R = Reset\")\n self.doFuncs()\n def spacePressed(self,event):\n print(self.going)\n self.going = not self.going\n #-----------------------------------------------------\n initial = -1*float(frameWidth-100)/2 + 5.1\n #initial = 0\n increase = 1.6\n sproites = {}\n functions = []\n def doFuncs(self):\n for i in self.getSpritesbyClass(drawnPoint):\n del i\n for i in range(0,len(self.functions)):\n try:\n b = funcInterpreter(\"y\",\"x\", self.functions[i][0], initial)[0]\n except:\n print(\"func failed\")\n try:\n b = funcInterpreter(\"y\",\"x\", self.functions[i][0], self.initial + self.increase / 2)[0]\n except:\n print(\"Function Failed, Going to (0,0)\", self.functions[i])\n b = (0,0)\n point((getX(b[0]),getY(b[1])), colorRandom(i), self.functions[i][0], self.functions[i][1])\n Sprite(TextAsset(self.functions[i][0], width=100, align='center',style='12px Arial', fill=black),(5,(i)*frameHeight/20+2))\n print(self.functions[i][0], self.functions[i][1])\n t = initial\n def step(self):\n g = self.increase\n if self.going == False:\n self.t = self.initial\n if self.going == True:\n self.t += g\n funcNumber = 0\n for sprite in self.getSpritesbyClass(point):\n funcNumber += 1\n indepVar = {\"y\":\"x\",\"x\":\"y\"}\n try:\n a = funcInterpreter(sprite.depVar,indepVar[sprite.depVar],sprite.equation,self.t)\n b = funcInterpreter(sprite.depVar,indepVar[sprite.depVar],sprite.equation,self.t - g)\n except:\n try:\n a = funcInterpreter(sprite.depVar,indepVar[depVar],sprite.equation,self.t + g / 2)\n b = funcInterpreter(sprite.depVar,indepVar[depVar],sprite.equation,self.t - 1 + g / 2)\n except:\n a = [(0,0)]\n b = [(0,0)]\n if isinstance(b, (list,)):\n sprite.x = getX(((a[0])[0]))\n sprite.y = getY(((a[0])[1]))\n else:\n sprite.x = getX(a[0])\n sprite.y = getY(a[0])\n print(\"Maybe something is off?\")\n drawnPoint.func((sprite.x,sprite.y),colorRandom(funcNumber))\nmyapp = Grapher(frameWidth, frameHeight)\nmyapp.run()","sub_path":"finalproject.py","file_name":"finalproject.py","file_ext":"py","file_size_in_byte":24787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"491338457","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\n\nfrom CMS.enums import enums\nfrom core.utils import get_page_for_language\nfrom coursefinder.forms import FilterForm, SearchForm\nfrom coursefinder.models import CourseSearch, CourseFinderSearch, CourseFinderUni, CourseFinderPostcode, \\\n CourseFinderSummary\nfrom coursefinder.models import CourseFinderResults\nfrom courses.models import CourseComparisonPage, CourseManagePage\n\n\ndef results(request, language=enums.languages.ENGLISH):\n query_params = request.GET\n search_form = SearchForm(query_params)\n course_search = CourseSearch(query_params.get('subject_query', \"\"), query_params.get('institution_query', \"\"),\n query_params.get('page', 1), query_params.get('count', 20))\n error = course_search.execute()\n\n if error:\n return render(request, '500.html')\n\n page = get_page_for_language(language, CourseFinderResults.objects.all())\n\n if not page:\n return render(request, '404.html')\n\n comparison_page = get_page_for_language(language, CourseComparisonPage.objects.all())\n bookmark_page = get_page_for_language(language, CourseManagePage.objects.all())\n\n full_path = '%s?%s' % (request.path, request.environ.get('QUERY_STRING'))\n welsh_url = '/cy' + full_path if language == enums.languages.ENGLISH else full_path\n english_url = full_path.replace('/cy/', '/')\n\n context = {\n 'page': page,\n 'search': course_search,\n 'pagination_url': 'results',\n 'comparison_link': comparison_page.url if comparison_page else '#',\n 'manage_link': bookmark_page.url if bookmark_page else '#',\n 'english_url': english_url,\n 'welsh_url': welsh_url,\n 'cookies_accepted': request.COOKIES.get('discoverUniCookies'),\n 'filter_form': search_form\n }\n\n return render(request, 'coursefinder/course_finder_results.html', context)\n\n\ndef narrow_search(request, language=enums.languages.ENGLISH):\n post_body = request.POST\n selection = post_body.get('radioGroup', None)\n if selection == \"uni\":\n page = get_page_for_language(language, CourseFinderUni.objects.all())\n elif selection == \"home\":\n page = get_page_for_language(language, CourseFinderPostcode.objects.all())\n else:\n page = get_page_for_language(language, CourseFinderSummary.objects.all())\n\n if page:\n return HttpResponseRedirect(page.url)\n return render(request, '404.html')\n\n\ndef course_finder_results(request, language=enums.languages.ENGLISH):\n query_params = request.POST\n countries_query = ','.join(query_params.getlist('countries_query')) if 'countries_query' in query_params else None\n filter_form = FilterForm(query_params)\n filters = build_filters(query_params)\n course_finder_search = CourseFinderSearch(query_params.get('subject_query', None),\n query_params.get('institution_query', None),\n countries_query,\n query_params.get('postcode_query', None),\n filters,\n query_params.get('course_query', None),\n query_params.get('page', 1),\n query_params.get('count', 20))\n error = course_finder_search.execute()\n\n if error:\n return render(request, '500.html')\n\n page = get_page_for_language(language, CourseFinderResults.objects.all())\n\n comparison_page = get_page_for_language(language, CourseComparisonPage.objects.all())\n bookmark_page = get_page_for_language(language, CourseManagePage.objects.all())\n\n welsh_url = '/cy' + request.path if language == enums.languages.ENGLISH else request.path\n english_url = request.path.replace('/cy/', '/')\n\n if not page:\n return render(request, '404.html')\n\n context = {\n 'page': page,\n 'search': course_finder_search,\n 'pagination_url': 'course_finder_results',\n 'comparison_link': comparison_page.url if comparison_page else '#',\n 'manage_link': bookmark_page.url if bookmark_page else '#',\n 'english_url': english_url,\n 'welsh_url': welsh_url,\n 'cookies_accepted': request.COOKIES.get('discoverUniCookies'),\n 'filter_form': filter_form\n }\n\n return render(request, 'coursefinder/course_finder_results.html', context)\n\n\ndef build_filters(params):\n filters = []\n\n if 'mode_query' in params:\n mode_query = ','.join(params.getlist('mode_query'))\n if 'Full-time,Part-time' not in mode_query:\n filters.append(params.get('mode_query').lower().replace('-', '_').replace(' ', '_'))\n if 'placement' in params:\n if params.get('placement') == 'yes':\n filters.append('sandwich_year')\n elif params.get('placement') == 'no':\n filters.append('-sandwich_year')\n if 'foundation' in params:\n if params.get('foundation') == 'yes':\n filters.append('foundation_year')\n elif params.get('foundation') == 'no':\n filters.append('-foundation_year')\n if 'abroad' in params:\n if params.get('abroad') == 'yes':\n filters.append('year_abroad')\n elif params.get('abroad') == 'no':\n filters.append('-year_abroad')\n\n return ','.join(filters)\n","sub_path":"coursefinder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"514713797","text":"import tensorflow as tf\r\nimport os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n# Creating variables\r\nwith tf.Graph().as_default():\r\n v = tf.Variable([5])\r\n w = tf.Variable(tf.random_normal([1], mean = 1.0, stddev = 0.35))\r\n\r\n with tf.Session() as sess:\r\n # try:\r\n # v.eval()\r\n # except tf.errors.FailedPreconditionError as e:\r\n # print('Caught exception: ', e)\r\n initializer = tf.global_variables_initializer()\r\n sess.run(initializer)\r\n print('v: ', v.eval(), '\\n w: ', w.eval())\r\n assign_v = tf.assign(v, [7])\r\n sess.run(assign_v) # rus without this statement also!\r\n print('New value of v: ', assign_v.eval())\r\n","sub_path":"Intro to TensorFlow/var_initiaz_assign.py","file_name":"var_initiaz_assign.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"243279194","text":"#!/usr/bin/python3\n\nfrom pathlib import Path\nfrom shutil import move\nfrom sys import argv\nimport asyncio\n\n\nasync def write_to(s, d):\n d.write(s.read())\n\n\nasync def merge_file(source, dest):\n with open(source, 'rb') as s, open(dest, 'ab') as d:\n await write_to(s, d)\n\n\nasync def main():\n \"\"\"\n Try to use asyncio.\n \"\"\"\n print('python3 amerge_folder.py source dest')\n source_dir = Path(argv[1]).absolute()\n dest_dir = Path(argv[2]).absolute()\n sources = set(i.name for i in source_dir.glob('*'))\n dests = set(i.name for i in dest_dir.glob('*'))\n to_merge = dests.intersection(sources)\n to_move = sources.difference(dests)\n for j in to_move:\n source = source_dir / j\n dest = dest_dir / j\n move(source, dest)\n for i in to_merge:\n source = source_dir / i\n dest = dest_dir / i\n asyncio.create_task(merge_file(source, dest))\n\n\nasyncio.run(main())\n","sub_path":"amerge_folder.py","file_name":"amerge_folder.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"594652332","text":"# binary search\nclass Solution:\n def splitArray(self, nums, k):\n def check(mid):\n cnt = 0\n cur_sum = 0\n for n in nums:\n if cur_sum + n > mid:\n cur_sum = 0\n cnt += 1\n if cnt >= k:\n return False\n cur_sum += n\n return True\n\n lo, hi = max(nums), sum(nums)\n\n while lo < hi:\n mid = lo + (hi - lo) // 2\n if check(mid):\n hi = mid\n else:\n lo = mid + 1\n return lo\n\n# DP\n# f[i][j] = max(f[k][j - 1], nums[k + 1] + ... + nums[i])\nclass Solution:\n def splitArray(self, nums, k):\n N = len(nums)\n dp = [[float('inf')] * (k + 1) for _ in range(N + 1)]\n acc = [0] + list(itertools.accumulate(nums))\n dp[0][0] = 0\n for i in range(1, N + 1): # 0 - i\n for j in range(1, k + 1): # j part\n for idx in range(i): # 0 - idx, j - 1 part; idx - i, 1 pary\n dp[i][j] = min(dp[i][j], max(dp[idx][j - 1], acc[i] - acc[idx]))\n\n return dp[-1][-1]\n","sub_path":"leetcode/py/410.py","file_name":"410.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"546540839","text":"import unittest\nimport ee\nfrom inst.python.sf_as_ee import *\nee.Initialize()\n\ndata_polygon = {\n \"type\": \"FeatureCollection\",\n \"features\": [{\"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\"type\": \"MultiPolygon\",\n \"coordinates\": [[[[-5, 40],\n [65, 40],\n [65, 60],\n [-5, 60],\n [-5, 60],\n [-5, 40]]]]\n}}]}\ndata_polygon = str(data_polygon)\nexpected_centroid = [30.000000000000004, 54.56306390486972]\n\nclass test_sf_as_ee(unittest.TestCase):\n def test_sf_as_ee_py(self):\n \"\"\"\n sf test: (Useful to testing future changes for earthengine-api)\n \"\"\"\n ee_data_polygon = ee_sf_as_ee_py(data_polygon)\n centroid_point = ee_data_polygon.geometry().centroid().getInfo()['coordinates']\n self.assertEqual(centroid_point[0], expected_centroid[0])\n self.assertEqual(centroid_point[1], expected_centroid[1])\n def test_sfc_as_ee_py(self):\n \"\"\"\n sfc test: (Useful to testing future changes for earthengine-api)\n \"\"\"\n sfc_export = str(eval(data_polygon)['features'][0]['geometry'])\n ee_data_polygon = ee_sfc_as_ee_py(sfc_export)\n centroid_point = ee_data_polygon.centroid().getInfo()['coordinates']\n self.assertEqual(centroid_point[0], expected_centroid[0])\n self.assertEqual(centroid_point[1], expected_centroid[1])\n def test_sfg_as_ee_py(self):\n \"\"\"\n sfg test: (Useful to testing future changes for earthengine-api)\n \"\"\"\n sfc_export = str(eval(data_polygon)['features'][0]['geometry'])\n ee_data_polygon = ee_sfg_as_ee_py(sfc_export)\n centroid_point = ee_data_polygon.centroid().getInfo()['coordinates']\n self.assertEqual(centroid_point[0], expected_centroid[0])\n self.assertEqual(centroid_point[1], expected_centroid[1])\n\nif __name__ == '__main__':\n unittest.main(\n failfast=False,\n buffer=False,\n catchbreak=False)\n","sub_path":"inst/tests/test_sf_as_ee.py","file_name":"test_sf_as_ee.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"356416749","text":"#! /usr/bin/env python3\nfrom collections import deque\n\ndef highest_score(number_of_players, last_marble):\n score = [ 0 for _ in range(number_of_players) ]\n circle = deque([ 0 ])\n\n next_number = 0\n turn = 0\n rotation = 0\n\n print_turn(turn - 1, circle, rotation)\n while next_number != last_marble:\n next_number += 1\n\n if next_number % 23 != 0:\n circle.rotate(-1)\n circle.append(next_number)\n rotation = (rotation + 2) % len(circle)\n else:\n score[turn] += next_number\n\n circle.rotate(7)\n\n score[turn] += circle.pop()\n\n circle.rotate(-1)\n rotation = (rotation - 5) % len(circle)\n\n print_turn(turn, circle, rotation)\n turn = (turn + 1) % number_of_players\n\n return max(score)\n\ndef print_turn(turn, circle, rotation = 0):\n circle = deque(circle)\n circle.rotate(rotation)\n\n current = (len(circle) - 1 + rotation) % len(circle)\n\n print('\\033[1;37m[{}]\\033[0m {}'.format(\n '-' if turn == -1 else turn + 1,\n ' '.join(\n '\\033[1;37m(\\033[0m\\033[1;33m{}\\033[1;37m)\\033[0m'.format(num) if i == current\\\n else '{}'.format(num)\n\n for i, num in enumerate(circle)\n )\n ))\n\nrecord = input().strip().split()\n\nnumber_of_players = int(record[0])\nlast_marble = int(record[6])\n\nprint(highest_score(number_of_players, last_marble ))\nprint(highest_score(number_of_players, last_marble * 100))\n","sub_path":"day09_print.py","file_name":"day09_print.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"202285615","text":"#coding:utf-8\nfrom selenium import webdriver\nimport unittest\nfrom Page import *\nfrom ddt import ddt,data,unpack\n# from Page import ddtTest\n\n\n@ddt\n\nclass lecooPage(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get('http://192.168.99.1')\n self.driver.implicitly_wait(30)\n\n @data(*ddtTest.getList())\n\n @unpack\n\n def testfailLogin(self,data,expected):\n lecooLogin.login(self.driver,data)\n self.assertEqual(expected, lecooLogin.getError(self.driver))\n\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == '__main__':\n\n unittest.main(verbosity=2)\n\n\n","sub_path":"TestCase/test_lecoologin_ddt2.py","file_name":"test_lecoologin_ddt2.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"293122715","text":"from math import cos, sin, pi, sqrt\nfrom PyQt5 import QtWidgets, QtGui\nfrom Observer.Observer import Observer\nfrom PyQt5.QtCore import Qt\nfrom StrangeThings.Dict_Ala_JS import Dict\nimport numpy as np\n\nclass Model(Observer):\n\n def __init__(self, complexView, spacialView, controller):\n super(Model, self).__init__()\n self.controller = controller\n self.complexView = complexView\n self.spacialView = spacialView\n # Central dots for both of Views\n self.x_graph, self.y_graph = self.spacialView.width() / 2, self.spacialView.height() / 2\n self.x_complex, self.y_complex = self.complexView.width() / 2, self.complexView.height() / 2\n\n # Make Dictionaries with coordinates\n # Half of len of axis\n self.max_p = 75\n # Main Dots\n self.T = Dict(x=0, y=0,z=0)\n self.C = Dict(x=0, y=0,z=0)\n self.colors = {\"T1\": Qt.black,\n \"T2\": Qt.green,\n \"T3\": Qt.red,\n \"Tx\": Qt.yellow,\n \"Ty\": Qt.darkGreen,\n \"Tz\": Qt.cyan,\n \"Ty1\": Qt.darkMagenta,\n \"Ty3\": Qt.darkBlue,\n \"C1\": Qt.black,\n \"C2\": Qt.green,\n \"C3\": Qt.red,\n \"Cx\": Qt.yellow,\n \"Cy\": Qt.darkGreen,\n \"Cz\": Qt.cyan,\n \"Cy1\": Qt.darkMagenta,\n \"Cy3\": Qt.darkBlue,\n }\n\n self.dots3D = []\n self.dots2D = {}\n self.Axis = {}\n self.TComplex = {}\n self.CComplex = {}\n # Bool Flag for type of projection\n self.orthographicProjection = False\n # Setting Default views\n self.update_me(\"TPoint&CPoint\")\n\n def updateSpatial(self):\n \"\"\"\n Repainting Spatial View\n :return:\n \"\"\"\n\n self.spacialView.clear()\n if self.dots2D == False:\n self.spacialView.drawText(self.spacialView.width()/2-25, self.spacialView.height()/2-25, \"Ошибка: \" + self.error)\n return None\n # Draw Axis of Spacial View\n self.spacialView.drawLine(self.dots2D['x'][0], self.dots2D['x'][1],\n self.dots2D['-x'][0], self.dots2D['-x'][1])\n self.spacialView.drawLine(self.dots2D['y'][0], self.dots2D['y'][1],\n self.dots2D['-y'][0], self.dots2D['-y'][1])\n self.spacialView.drawLine(self.dots2D['z'][0], self.dots2D['z'][1],\n self.dots2D['-z'][0], self.dots2D['-z'][1])\n self.spacialView.drawText(self.dots2D['x'][0], self.dots2D['x'][1], \"x\")\n self.spacialView.drawText(self.dots2D['y'][0], self.dots2D['y'][1], \"y\")\n self.spacialView.drawText(self.dots2D['z'][0], self.dots2D['z'][1], \"z\")\n\n # Draw Connections Between Points\n self.spacialView.drawLine(self.dots2D['T'][0], self.dots2D['T'][1],\n self.dots2D['T2'][0], self.dots2D['T2'][1])\n self.spacialView.drawLine(self.dots2D['T'][0], self.dots2D['T'][1],\n self.dots2D['T3'][0], self.dots2D['T3'][1])\n self.spacialView.drawLine(self.dots2D['T1'][0], self.dots2D['T1'][1],\n self.dots2D['T'][0], self.dots2D['T'][1])\n self.spacialView.drawLine(self.dots2D['T1'][0], self.dots2D['T1'][1],\n self.dots2D['Tx'][0], self.dots2D['Tx'][1])\n self.spacialView.drawLine(self.dots2D['T1'][0], self.dots2D['T1'][1],\n self.dots2D['Ty'][0], self.dots2D['Ty'][1])\n self.spacialView.drawLine(self.dots2D['T2'][0], self.dots2D['T2'][1],\n self.dots2D['Tz'][0], self.dots2D['Tz'][1])\n self.spacialView.drawLine(self.dots2D['T3'][0], self.dots2D['T3'][1],\n self.dots2D['Ty'][0], self.dots2D['Ty'][1])\n self.spacialView.drawLine(self.dots2D['Tx'][0], self.dots2D['Tx'][1],\n self.dots2D['T2'][0], self.dots2D['T2'][1])\n self.spacialView.drawLine(self.dots2D['Tz'][0], self.dots2D['Tz'][1],\n self.dots2D['T3'][0], self.dots2D['T3'][1])\n\n # Draw 14 Points on Spacial View\n self.spacialView.drawMe(self.dots2D['O'][0], self.dots2D[\"O\"][1], \"O\")\n self.spacialView.drawMe(self.dots2D['T1'][0], self.dots2D['T1'][1], \"T1\", self.colors[\"T1\"])\n self.spacialView.drawMe(self.dots2D['T2'][0], self.dots2D['T2'][1], \"T2\", self.colors[\"T2\"])\n self.spacialView.drawMe(self.dots2D['T3'][0], self.dots2D['T3'][1], \"T3\", self.colors[\"T3\"])\n self.spacialView.drawMe(self.dots2D['Tx'][0], self.dots2D['Tx'][1], \"Tx\", self.colors[\"Tx\"])\n self.spacialView.drawMe(self.dots2D['Ty'][0], self.dots2D['Ty'][1], \"Ty\", self.colors[\"Ty\"])\n self.spacialView.drawMe(self.dots2D['Tz'][0], self.dots2D['Tz'][1], \"Tz\", self.colors[\"Tz\"])\n self.spacialView.drawMe(self.dots2D['T'][0], self.dots2D['T'][1], \"T\")\n\n def updateComplex(self):\n\n self.complexView.clear()\n # Draw Axis of Complex View and Point 'O'\n self.complexView.drawLine(self.Axis['x'][0], self.Axis['x'][1],\n self.Axis['y3'][0], self.Axis['y3'][1])\n self.complexView.drawLine(self.Axis['z'][0], self.Axis['z'][1],\n self.Axis['y1'][0], self.Axis['y1'][1])\n self.complexView.drawText(self.Axis['x'][0], self.Axis['x'][1], \"x\")\n self.complexView.drawText(self.Axis['y3'][0], self.Axis['y3'][1], \"y3\")\n self.complexView.drawText(self.Axis['y1'][0], self.Axis['y1'][1], \"y1\")\n self.complexView.drawText(self.Axis['z'][0], self.Axis['z'][1], \"z\")\n self.complexView.drawMe(self.Axis['O'][0], self.Axis['O'][1], \"O\")\n\n # Draw 11(without point 'O') Complex Points that relate to the T point\n self.complexView.drawMe(self.TComplex['Tx'][0], self.TComplex['Tx'][1], \"Tx\", self.colors[\"Tx\"])\n self.complexView.drawMe(self.TComplex['Ty1'][0], self.TComplex['Ty1'][1], \"Ty1\", self.colors[\"Ty1\"])\n self.complexView.drawMe(self.TComplex['Ty3'][0], self.TComplex['Ty3'][1], \"Ty3\", self.colors[\"Ty3\"])\n self.complexView.drawMe(self.TComplex['Tz'][0], self.TComplex['Tz'][1], \"Tz\", self.colors[\"Tz\"])\n self.complexView.drawMe(self.TComplex['T1'][0], self.TComplex['T1'][1], \"T1\", self.colors[\"T1\"])\n self.complexView.drawMe(self.TComplex['T2'][0], self.TComplex['T2'][1], \"T2\", self.colors[\"T2\"])\n self.complexView.drawMe(self.TComplex['T3'][0], self.TComplex['T3'][1], \"T3\", self.colors[\"T3\"])\n # Draw Connections Between Points realted to the T point\n self.complexView.drawLine(self.TComplex['T1'][0], self.TComplex['T1'][1],\n self.TComplex['T2'][0], self.TComplex['T2'][1])\n self.complexView.drawLine(self.TComplex['T2'][0], self.TComplex['T2'][1],\n self.TComplex['T3'][0], self.TComplex['T3'][1])\n self.complexView.drawLine(self.TComplex['T3'][0], self.TComplex['T3'][1],\n self.TComplex['Ty3'][0], self.TComplex['Ty3'][1])\n self.complexView.drawLine(self.TComplex['T1'][0], self.TComplex['T1'][1],\n self.TComplex['Ty1'][0], self.TComplex['Ty1'][1])\n\n width = 2 * (self.TComplex['Ty3'][0] - self.TComplex['Ty1'][0])\n height = 2 * (self.TComplex['Ty1'][1] - self.TComplex['Ty3'][1])\n startAngle = 270 if self.TComplex['T3'][0] > self.Axis[\"O\"][0] else 90\n self.complexView.drawArc(self.TComplex['Ty3'][0] - width,\n self.TComplex['Ty1'][1] - height,\n width, height,\n startAngle)\n\n # Draw 11(without point 'O') Complex Points that related to the C point\n self.complexView.drawMe(self.CComplex[\"Cx\"][0], self.CComplex[\"Cx\"][1], \"Cx\", self.colors[\"Cx\"])\n self.complexView.drawMe(self.CComplex['Cy1'][0], self.CComplex['Cy1'][1], \"Cy1\", self.colors[\"Cy1\"])\n self.complexView.drawMe(self.CComplex['Cy3'][0], self.CComplex['Cy3'][1], \"Cy3\", self.colors[\"Cy3\"])\n self.complexView.drawMe(self.CComplex['Cz'][0], self.CComplex['Cz'][1], \"Cz\", self.colors[\"Cz\"])\n self.complexView.drawMe(self.CComplex['C1'][0], self.CComplex['C1'][1], \"C1\", self.colors[\"C1\"])\n self.complexView.drawMe(self.CComplex['C2'][0], self.CComplex['C2'][1], \"C2\", self.colors[\"C2\"])\n self.complexView.drawMe(self.CComplex['C3'][0], self.CComplex['C3'][1], \"C3\", self.colors[\"C3\"])\n # Draw Connections Between Points related to the C point\n self.complexView.drawLine(self.CComplex['C1'][0], self.CComplex['C1'][1],\n self.CComplex['C2'][0], self.CComplex['C2'][1])\n self.complexView.drawLine(self.CComplex['C2'][0], self.CComplex['C2'][1],\n self.CComplex['C3'][0], self.CComplex['C3'][1])\n self.complexView.drawLine(self.CComplex['C3'][0], self.CComplex['C3'][1],\n self.CComplex['Cy3'][0], self.CComplex['Cy3'][1])\n self.complexView.drawLine(self.CComplex['C1'][0], self.CComplex['C1'][1],\n self.CComplex['Cy1'][0], self.CComplex['Cy1'][1])\n\n width = 2 * (self.CComplex['Cy3'][0] - self.CComplex['Cy1'][0])\n height = 2 * (self.CComplex['Cy1'][1] - self.CComplex['Cy3'][1])\n startAngle = 270 if self.CComplex['C3'][0] > self.Axis[\"O\"][0] else 90\n self.complexView.drawArc(self.CComplex['Cy3'][0] - width,\n self.CComplex['Cy1'][1] - height,\n width, height,\n startAngle)\n def getSpacialDots(self):\n self.getOrthSpacial() if self.orthographicProjection else self.getCentralSpacial()\n\n def getOrthSpacial(self):\n # Restore dot2D type to default\n self.dots2D = {}\n # First Inspection\n if self.C.x == self.C.y == self.C.z == 0:\n self.dots2D = False\n self.error = \"C.x = C.y = 0\"\n return None\n # Values of sin and cos depends on x & y coordinates of C point\n if self.C.x == self.C.y == 0:\n sinχ = 0\n cosχ = 1\n else:\n cosχ = self.C.y / sqrt(self.C.x ** 2 + self.C.y ** 2)\n sinχ = self.C.x / sqrt(self.C.x ** 2 + self.C.y ** 2)\n # Rotating around Z-axis Matrix\n Rz = np.array([\n [cosχ, sinχ, 0, 0],\n [-sinχ, cosχ, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n # Rotating around X-axis Matrix\n Rx = np.array([\n [1, 0, 0, 0],\n [0, self.C.z / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2),\n sqrt(self.C.x ** 2 + self.C.y ** 2) / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2), 0],\n [0, -sqrt(self.C.x ** 2 + self.C.y ** 2) / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2),\n self.C.z / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2), 0],\n [0, 0, 0, 1]\n ])\n # Matrix of moving Point to it's place on the screen\n # Or in general moving coordinate system to the edge of the screen\n T = np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n # [self.dots3D[0][\"O\"][0], self.dots3D[0][\"O\"][1], 0, 1]\n [self.x_graph, self.y_graph, 0, 1]\n ])\n # Mirroring an X-axis Matrix\n Mx = np.array([\n [-1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n # projection on the Z Matrix\n Pz = np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]\n ])\n # Resulting Matrix A\n Mat = np.dot(Rz, Rx)\n Mat = np.dot(Mat, Mx, out=None)\n Mat = np.dot(Mat, Pz, out=None)\n Mat = np.dot(Mat, T, out=None)\n # Calculating coordinates of points on the screen plane\n for key in self.dots3D[0].keys():\n self.dots2D[key] = np.dot(np.array(self.dots3D[0][key]), Mat).tolist()\n for key in self.dots3D[1].keys():\n self.dots2D[key] = np.dot(np.array(self.dots3D[1][key]), Mat).tolist()\n\n def getCentralSpacial(self):\n # Restore dot2D type to default\n self.dots2D = {}\n # First Inspection\n if self.C.x == self.C.y == self.C.z == 0:\n self.dots2D = False\n self.error = \"C.x = C.y = 0\"\n return None\n # Second inspection whether cos of angle between T and C points positive\n if -self.C.x * (self.T.x - self.C.x) - self.C.y * (self.T.y - self.C.y) - self.C.z * (self.T.z - self.C.z) < 0:\n self.dots2D = False\n self.error = \"Cos < 0\"\n return None\n # Values of sin and cos depends on x & y coordinates of C point\n if self.C.x == self.C.y == 0:\n sinχ = 0\n cosχ = 1\n else:\n cosχ = self.C.y / sqrt(self.C.x ** 2 + self.C.y ** 2)\n sinχ = self.C.x / sqrt(self.C.x ** 2 + self.C.y ** 2)\n # Rotating around Z-axis Matrix\n Rz = np.array([\n [cosχ, sinχ, 0, 0],\n [-sinχ, cosχ, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n # Rotating around X-axis Matrix\n Rx = np.array([\n [1, 0, 0, 0],\n [0, self.C.z / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2),\n sqrt(self.C.x ** 2 + self.C.y ** 2) / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2), 0],\n [0, -sqrt(self.C.x ** 2 + self.C.y ** 2) / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2),\n self.C.z / sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2), 0],\n [0, 0, 0, 1]\n ])\n # Matrix of moving Point to it's place on the screen\n # Or in general moving coordinate system to the edge of the screen\n T = np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [self.x_graph, self.y_graph, 0, 1]\n ])\n # Mirroring an X-axis Matrix\n Mx = np.array([\n [-1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ])\n # projection on the Z Matrix\n Pz = np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 1]\n ])\n Cz = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, -1 / (sqrt(self.C.x ** 2 + self.C.y ** 2 + self.C.z ** 2))],\n [0, 0, 0, 1]\n ]\n # Resulting Matrix B\n Mat = np.dot(Rz, Rx)\n Mat = np.dot(Mat, Mx)\n Mat = np.dot(Mat, Cz)\n Mat = np.dot(Mat, Pz)\n Mat = np.dot(Mat, T)\n # Calculating coordinates of points on the screen plane\n for key in self.dots3D[0].keys():\n point = np.dot(np.array(self.dots3D[0][key]), Mat)\n point = point.tolist()\n if point[3] == 0:\n self.dots2D = None\n print(\"Error:\", key, point)\n return\n self.dots2D[key] = [point[0]/point[3], point[1]/point[3]]\n for key in self.dots3D[1].keys():\n point = np.dot(np.array(self.dots3D[1][key]), Mat)\n point = point.tolist()\n if point[3] == 0:\n self.dots2D = None\n print(\"Error:\", key, point)\n return\n self.dots2D[key] = [point[0]/point[3], point[1]/point[3]]\n\n for point in self.dots2D.values():\n if point[0] < 0 or point[0] > self.spacialView.width() or point[1] < 0 or point[1] > self.spacialView.height():\n self.dots2D = False\n self.error = \"Точки вне области рисования\"\n return\n\n def getComplexDots(self):\n \"\"\"\n Make Points for Complex GR\n :return:\n \"\"\"\n self.getComplexT()\n self.getComplexC()\n self.getComplexAxis()\n\n def getComplexAxis(self):\n self.Axis = {\n \"O\": self.T1(self.x_complex, self.y_complex, self.dots3D[0][\"O\"]),\n \"z\": self.T3(self.x_complex, self.y_complex, self.dots3D[0][\"z\"]),\n \"x\": self.T1(self.x_complex, self.y_complex, self.dots3D[0][\"x\"]),\n \"y1\": self.T3(self.x_complex, self.y_complex, self.dots3D[0][\"-z\"]),\n \"y3\": self.T1(self.x_complex, self.y_complex, self.dots3D[0][\"-x\"])\n }\n\n def getComplexT(self):\n self.TComplex = {\n \"Tx\": self.T1(self.x_complex, self.y_complex, self.dots3D[1][\"Tx\"]),\n \"Tz\": self.T3(self.x_complex, self.y_complex, self.dots3D[1][\"Tz\"]),\n \"Ty1\": self.T1(self.x_complex, self.y_complex, self.dots3D[1][\"Ty\"]),\n \"Ty3\": self.T3(self.x_complex, self.y_complex, self.dots3D[1][\"Ty\"]),\n \"T1\": self.T1(self.x_complex, self.y_complex, self.dots3D[1][\"T1\"]),\n \"T2\": self.T2(self.x_complex, self.y_complex, self.dots3D[1][\"T2\"]),\n \"T3\": self.T3(self.x_complex, self.y_complex, self.dots3D[1][\"T3\"])\n }\n\n def getComplexC(self):\n if not self.orthographicProjection:\n self.CComplex = {\n \"Cx\": self.T1(self.x_complex, self.y_complex, self.dots3D[2][\"Cx\"]),\n \"Cz\": self.T3(self.x_complex, self.y_complex, self.dots3D[2][\"Cz\"]),\n \"Cy1\": self.T1(self.x_complex, self.y_complex, self.dots3D[2][\"Cy\"]),\n \"Cy3\": self.T3(self.x_complex, self.y_complex, self.dots3D[2][\"Cy\"]),\n \"C1\": self.T1(self.x_complex, self.y_complex, self.dots3D[2][\"C1\"]),\n \"C2\": self.T2(self.x_complex, self.y_complex, self.dots3D[2][\"C2\"]),\n \"C3\": self.T3(self.x_complex, self.y_complex, self.dots3D[2][\"C3\"])\n }\n elif self.orthographicProjection:\n infinity = 120\n self.CComplex = {\n \"Cx\": self.T1(self.x_complex, self.y_complex, [infinity, 0, 0, 0]),\n \"Cz\": self.T3(self.x_complex, self.y_complex, [0, 0 , infinity, 0]),\n \"Cy1\": self.T1(self.x_complex, self.y_complex, [0, infinity, 0, 0]),\n \"Cy3\": self.T3(self.x_complex, self.y_complex,[0, infinity, 0, 0]),\n \"C1\": self.T1(self.x_complex, self.y_complex, [infinity, infinity, 0, 0]),\n \"C2\": self.T2(self.x_complex, self.y_complex, [infinity, 0, infinity, 0]),\n \"C3\": self.T3(self.x_complex, self.y_complex, [0, infinity, infinity, 0])\n }\n\n def update_me(self, who):\n # Which Projection to picture\n if who == \"stateChanged\":\n self.getType()\n self.getDots()\n self.getSpacialDots()\n else:\n self.getDots()\n self.getSpacialDots()\n self.getComplexDots()\n self.updateComplex()\n self.updateSpatial()\n\n # Getters\n def getDots(self):\n self.dots3D = self.controller.dots3D\n self.T = Dict(x=self.dots3D[1][\"T\"][0], y=self.dots3D[1][\"T\"][1], z=self.dots3D[1][\"T\"][2])\n self.C = Dict(x=self.dots3D[2][\"C\"][0], y=self.dots3D[2][\"C\"][1], z=self.dots3D[2][\"C\"][2])\n\n def getType(self):\n self.orthographicProjection = self.controller.getType()\n\n @staticmethod\n def T1(x, y, dot):\n return [x - dot[0], y + dot[1]]\n\n @staticmethod\n def T2(x, y, dot):\n return [x - dot[0], y - dot[2]]\n\n @staticmethod\n def T3(x, y, dot):\n return [x + dot[1], y - dot[2]]\n","sub_path":"KG/Lab2/Model/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":19881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"180984382","text":"from flask import Flask\r\nfrom flask import request\r\nimport json\r\nimport os\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\", methods = ['GET', 'POST', 'DELETE'])\r\ndef state_name():\r\n if request.method == 'GET':\r\n\r\n if (\"USER\" in os.environ):\r\n USER = str(os.getenv('USER'))\r\n else:\r\n USER = \"NotinLocal\"\r\n\r\n if (\"LASTNAME\" in os.environ):\r\n LASTNAME = str(os.getenv('LASTNAME'))\r\n else:\r\n LASTNAME = \"NotinLocal\"\r\n\r\n if (\"THIRDNAME\" in os.environ):\r\n THIRDNAME = str(os.getenv('THIRDNAME'))\r\n else:\r\n THIRDNAME = \"NotinLocal\"\r\n\r\n json_string = '{ \"USER\":\"' + USER + '\", \"LASTNAME\":\"' + LASTNAME +'\", \"THIRDNAME\":\"' + THIRDNAME +'\"}'\r\n \r\n data = json.loads(json_string)\r\n\r\n return(data)\r\n\r\n if request.method == 'POST':\r\n\r\n USER = request.args.get(\"USER\")\r\n if not (isinstance(USER, str)):\r\n USER = \"NonePosted\"\r\n os.environ[\"USER\"] = USER\r\n\r\n LASTNAME = request.args.get(\"LASTNAME\")\r\n if not (isinstance(LASTNAME, str)):\r\n LASTNAME = \"NonePosted\"\r\n os.environ[\"LASTNAME\"] = LASTNAME\r\n\r\n THIRDNAME = request.args.get(\"THIRDNAME\")\r\n if not (isinstance(THIRDNAME, str)):\r\n THIRDNAME = \"NonePosted\"\r\n os.environ[\"THIRDNAME\"] = THIRDNAME\r\n \r\n json_string = '{ \"USER\":\"' + USER + '\", \"LASTNAME\":\"' + LASTNAME +'\", \"THIRDNAME\":\"' + THIRDNAME +'\"}'\r\n \r\n data = json.loads(json_string)\r\n\r\n return(data)\r\n\r\n if request.method == 'DELETE':\r\n\r\n os.environ.pop(\"USER\")\r\n os.environ.pop(\"LASTNAME\")\r\n os.environ.pop(\"THIRDNAME\")\r\n\r\n json_string = '{ \"USER\":\"JustDeleted\", \"LASTNAME\":\"JustDeleted\", \"THIRDNAME\":\"JustDeleted\"}'\r\n \r\n data = json.loads(json_string)\r\n\r\n return(data)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host = \"0.0.0.0\", port=3333, debug = True)","sub_path":"DummyAPI/DummyAPI.py","file_name":"DummyAPI.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"520611532","text":"from pyqtgraph import PlotWidget, mkPen\nimport pyqtgraph as pg\nfrom random import randint\n\nclass Plot(PlotWidget):\n def __init__(self, parent):\n\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n\n self.penNumber = 0\n\n PlotWidget.__init__(self, parent)\n self.plotItem = self.getPlotItem()\n\n self.plotItem.setMouseEnabled(x=False, y=False)\n self.plotItem.setMenuEnabled(False)\n\n self.activatePlot = self.plotItem.plot([0, 1], [0, 1], pen=self.getRandomPen(), autoDownsample=True, downsampleMethod='subsample')\n self.viewBox = self.plotItem.getViewBox()\n\n def init(self, measurementService):\n self.measurementService = measurementService\n self.wireSignals()\n\n def wireSignals(self):\n self.measurementService.updatePlot.connect(self.plotUpdate)\n self.measurementService.labelPlot.connect(self.label)\n self.measurementService.addPlot.connect(self.addPlot)\n self.measurementService.clearPlot.connect(self.clearPlot)\n self.measurementService.setXRange.connect(self.changeXRange)\n\n def plotUpdate(self):\n activateData = self.measurementService.currentMeasurement.getCurrentPlotData()\n self.activatePlot.setData(activateData[0], activateData[1])\n\n def addPlot(self, tuple):\n self.plotItem.plot(tuple[0], tuple[1], pen=self.getRandomPen(), autoDownsample=True, downsampleMethod='subsample')\n\n def label(self, parameter):\n self.plotItem.setTitle(parameter['title'])\n self.plotItem.setLabel('left', text=parameter['y-label'], units=parameter['y-unit'], unitPrefix=None)\n self.plotItem.setLabel('bottom', text=parameter['x-label'], units=parameter['x-unit'], unitPrefix=None)\n\n def clearPlot(self):\n self.plotItem.clear()\n self.activatePlot = self.plotItem.plot([], [], pen=self.getRandomPen())\n\n def changeXRange(self, values):\n self.viewBox.setXRange(*values, padding=0.02, update=False)\n\n def getRandomPen(self):\n colors = [\n (0, 188, 212),\n (139, 195, 74),\n (255, 192, 7),\n (96, 125, 139),\n (76, 175, 80),\n (103, 58, 183),\n (205, 220, 57)\n ]\n\n pen = mkPen(colors[self.penNumber], width=2)\n\n if self.penNumber + 1 == len(colors):\n self.penNumber = 0\n else:\n self.penNumber += 1\n\n return pen","sub_path":"Controllers/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"113253423","text":"import functools\nfrom PIL import Image\nimport sys\nfrom PyQt5 import QtCore, QtWidgets\nfrom clutil.gui.CLWindow import CLWindow\nfrom clutil.gui.CLCanvas import CLCanvas\nfrom clutil.Brush import Brush\nfrom clutil.Colorize import Colorize\nfrom clutil.utils import roundUp, padArray2D\nfrom clutil.GrowCut import GrowCut\nfrom clutil.Buffer2D import Buffer2D\nfrom clutil.Image2D import Image2D\nimport numpy as np\nimport pyopencl as cl\ncm = cl.mem_flags\n\nimg = Image.open(\"/Users/marcdeklerk/msc/dataset/in/832x640/GT04.png\")\n# img = Image.open(\"/Users/marcdeklerk/msc/dataset/in/2048x1536/GT04.png\")\nif img.mode != 'RGBA':\n img = img.convert('RGBA')\n\napp = QtWidgets.QApplication(sys.argv)\ncanvas = CLCanvas(img.size)\nwindow = CLWindow(canvas)\n\nclContext = canvas.context\ndevices = clContext.get_info(cl.context_info.DEVICES)\nqueue = cl.CommandQueue(clContext, properties=cl.command_queue_properties.PROFILING_ENABLE)\n\nshape = (img.size[1], img.size[0])\nshape = roundUp(shape, GrowCut.lw)\ndim = (shape[1], shape[0])\n\nhImg = padArray2D(np.array(img).view(np.uint32).squeeze(), shape, 'edge')\n\ndImg = Image2D(clContext,\n cl.mem_flags.READ_ONLY,\n cl.ImageFormat(cl.channel_order.RGBA, cl.channel_type.UNSIGNED_INT8),\n dim\n)\ncl.enqueue_copy(queue, dImg, hImg, origin=(0, 0), region=dim).wait()\n\ndStrokes = Buffer2D(clContext, cm.READ_WRITE, dim, dtype=np.uint8)\n\nbrush = Brush(clContext, devices, dStrokes)\n\ngrowCut = GrowCut(clContext, devices, dImg, GrowCut.NEIGHBOURHOOD.VON_NEUMANN, GrowCut.WEIGHT_DEFAULT)\n\nlabel = 1\n\niteration = 0\nrefresh = 100\n\ndef update():\n global iteration\n\n growCut.evolve(1)\n\n if growCut.isComplete:\n window.updateCanvas()\n timer.stop()\n return\n\n if iteration % refresh == 0:\n window.updateCanvas()\n\n iteration += 1\n\ndef mouseDrag(pos1, pos2):\n if pos1 == pos2:\n return\n\n timer.stop()\n brush.draw(pos1, pos2)\n growCut.label(brush.d_points, brush.n_points, brush.label)\n\n window.updateCanvas()\n\n timer.start()\n\ndef mousePress(pos):\n mouseDrag(pos, None)\n\ndef keyPress(key):\n global label\n\n if key == QtCore.Qt.Key_1: brush.setLabel(1)\n elif key == QtCore.Qt.Key_2: brush.setLabel(2)\n elif key == QtCore.Qt.Key_3: brush.setLabel(3)\n elif key == QtCore.Qt.Key_4: brush.setLabel(4)\n elif key == QtCore.Qt.Key_5: brush.setLabel(5)\n elif key == QtCore.Qt.Key_6: brush.setLabel(6)\n elif key == QtCore.Qt.Key_7: brush.setLabel(7)\n elif key == QtCore.Qt.Key_8: brush.setLabel(8)\n\ntimer = QtCore.QTimer()\ntimer.timeout.connect(update)\n\n#setup window\nfilter = Colorize(clContext, (0, 8), Colorize.HUES.STANDARD)\n\nwindow.addLayer('labels', growCut.dLabelsIn, 0.5, filters=[filter])\nwindow.addLayer('labels', growCut.dLabelsOut, 0.5, filters=[filter])\nwindow.addLayer('strokes', dStrokes, 0.25, filters=[filter])\nfilter = Colorize(clContext, (0, 1.0), hues=Colorize.HUES.REVERSED)\nwindow.addLayer('strength', growCut.dStrengthIn, 1.0, filters=[filter])\nwindow.addLayer('image', dImg)\nwindow.addLayer('tiles', growCut.tilelist, filters=[growCut.tilelist])\n\nwindow.addButton(\"save\", functools.partial(timer.start, 0))\nwindow.addButton('load', next)\nwindow.setMousePress(mousePress)\nwindow.setMouseDrag(mouseDrag)\nwindow.setKeyPress(keyPress)\n\nwindow.resize(1000, 700)\nwindow.show()\nsys.exit(app.exec_())","sub_path":"tests/test_GrowCut.py","file_name":"test_GrowCut.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"512866472","text":"# -*- coding:utf-8 -*-\n\n#包含中间所有的格式的转换,主要是Bert生成的答案 只有ID和预测,需要更改。\nimport json\n\n# 只有训练集的时候,我训练了search集,想自己evaluate下,所以要通过这个更改输出的格式,现在木用了\n# 从输出的prediction文件,按照ID补全信息生成 pred 和 ref 两个文件。\ndef fulfil_prediction_train(raw_path,prediction_path,ref_path,pre_path):\n def get_pred(yesno,question,q_type,answers,question_id):\n return{\n \"yesno_answers\":yesno,\n \"question\": question,\n \"question_type\":q_type,\n \"answers\":answers,\n \"question_id\":question_id\n }\n\n\n def get_ref(entity,yesno,question,q_type,answers,question_id):\n return{\n \"entity_answers\": entity,\n \"yesno_answers\":yesno,\n \"question\": question,\n \"question_type\":q_type,\n \"answers\":answers,\n \"source\": \"search\",\n \"question_id\":question_id\n }\n\n path = 'C:\\\\Users\\\\workstation\\\\Desktop\\\\predictions.json'\n pre_path = \"F:\\TriB-QA\\data\\pred.json\"\n ref_path = \"F:\\TriB-QA\\data\\\\ref.json\"\n\n\n with open(path,encoding='utf-8') as f:\n data = json.load(f)\n id = list(int(i) for i in data.keys())\n\n ref_writer = open(ref_path,'w',encoding='utf-8')\n pre_writer = open(pre_path,'w',encoding='utf-8')\n with open(\"D:\\迅雷下载\\\\train_preprocessed\\\\train_preprocessed\\\\trainset\\\\search.train.json\",encoding = 'utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n\n if int(example['question_id']) not in id :\n continue\n q_id = example['question_id']\n question = example['question']\n q_type = example['question_type']\n answers = example['answers']\n yesno = []\n entity = [[]]\n pred = data[str(q_id)]\n cleaned_pre = [''.join(pred.split())]\n pre = get_pred(yesno,question,q_type,cleaned_pre,q_id)\n pre_writer.write(json.dumps(pre, ensure_ascii=False))\n pre_writer.write('\\n')\n if q_type == \"ENTITY\":\n entity = example['entity_answers']\n elif q_type == \"YES_NO\":\n yesno = example['yesno_answers']\n else:\n pass\n ref = get_ref(entity,yesno,question,q_type,answers,q_id)\n ref_writer.write(json.dumps(ref,ensure_ascii=False))\n ref_writer.write('\\n')\n\n ref_writer.close()\n pre_writer.close()\n\n\n\n# Bert预测训练的时候目前是分开的,search 和 zhidao 分开。所以我要将两个合在一起并补足信息。\n# 输出的output 文件 需要进一步放到YES No\n\ndef fulfil_prediction_test1(raw_zhidao_path=\"F:\\TriB-QA\\\\test1\\zhidao.test1.json\",raw_search_path = \"F:\\TriB-QA\\\\test1\\search.test1.json\",pred_zhidao = 'F:\\TriB-QA\\\\test1\\\\test_zhidao_1_predictions.json',pred_search = 'F:\\TriB-QA\\\\test1\\\\test_search_1_predictions.json',output=\"F:\\TriB-QA\\\\test1\\\\pred_1.json\"):\n\n def get_pred(question_id,q_type,answers,yesno):\n return{\n \"question_id\": question_id,\n \"question_type\": q_type,\n \"answers\": answers,\n \"yesno_answers\":yesno\n }\n with open(pred_zhidao,encoding='utf-8') as f:\n data = json.load(f)\n id = list(int(i) for i in data.keys())\n pre_writer = open(output,'w',encoding='utf-8')\n with open(raw_zhidao_path,encoding = 'utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n\n if int(example['question_id']) not in id :\n continue\n q_id = example['question_id']\n q_type = example['question_type']\n yesno = []\n pred = data[str(q_id)]\n cleaned_pre = [''.join(pred.split())]\n pre = get_pred(q_id,q_type,cleaned_pre,yesno)\n pre_writer.write(json.dumps(pre, ensure_ascii=False))\n pre_writer.write('\\n')\n print('finished ZHIDAO')\n with open(pred_search,encoding='utf-8') as f:\n data = json.load(f)\n id = list(int(i) for i in data.keys())\n\n with open(raw_search_path,encoding = 'utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n\n if int(example['question_id']) not in id :\n continue\n q_id = example['question_id']\n q_type = example['question_type']\n yesno = []\n pred = data[str(q_id)]\n cleaned_pre = [''.join(pred.split())]\n pre = get_pred(q_id,q_type,cleaned_pre,yesno)\n pre_writer.write(json.dumps(pre, ensure_ascii=False))\n pre_writer.write('\\n')\n pre_writer.close()\n\n\n# 把上面的outpu 中YESno 提取出来。号输入到分类BERT\ndef YES_NO_filter():\n f = open(\"F:\\TriB-QA\\\\test1\\pred1.json\", \"r\", encoding='utf-8')\n yes_no_dev = {}\n readlines = f.readlines()\n\n total = 0\n\n for each in readlines:\n json_dicts = json.loads(each)\n if json_dicts[\"question_type\"] == \"YES_NO\":\n pos = 0\n\n for each_answer in json_dicts[\"answers\"]:\n tmp = {}\n\n tmp[\"question_id\"] = json_dicts[\"question_id\"]\n tmp[\"answer\"] = each_answer\n tmp[\"question_type\"] = json_dicts[\"question_type\"]\n tmp[\"yesno_answers\"] = 2\n\n if \"yesno_type\" in json_dicts.keys():\n tmp[\"yesno_type\"] = json_dicts[\"yesno_type\"]\n print(str(total) + '\\r', end='')\n yes_no_dev[json_dicts[\"question_id\"]] = tmp\n\n pos += 1\n total += 1\n\n str0 = json.dumps(yes_no_dev, ensure_ascii=False)\n fout = open(\"F:\\TriB-QA\\\\test1\\dev1.json\", 'w', encoding='utf-8')\n fout.write(str0)\n fout.close()\n\n\n# YES NO判断完毕也有一个文件,将这个文件与前面文件合并\n# 最后输出result文件\ndef Build_final_result(Yes_No=\"F:\\TriB-QA\\\\test1\\output0.txt\",pre_path=\"F:\\TriB-QA\\\\test1\\\\pred1.json\",result=\"F:\\TriB-QA\\\\test1\\\\result1.json\"):\n\n def get_pred(question_id,q_type,answers,yesno):\n return{\n \"question_id\": question_id,\n \"question_type\": q_type,\n \"answers\": answers,\n \"yesno_answers\":yesno\n }\n YES_NO_QUESTION = {}\n with open(Yes_No,encoding='utf-8') as f:\n for line in f:\n example = json.loads(line)\n YES_NO = example['yesno_answers']\n QID = int(example['question_id'])\n YES_NO_QUESTION[QID] = YES_NO\n\n id = list(YES_NO_QUESTION.keys())\n\n writer = open(result,'w',encoding='utf-8')\n with open(pre_path,encoding='utf-8') as f:\n for line in f:\n example = json.loads(line)\n if int(example['question_id']) not in id or example['question_type'] != \"YES_NO\":\n writer.write(json.dumps(example,ensure_ascii=False))\n writer.write('\\n')\n continue\n q_type = example['question_type']\n assert q_type == \"YES_NO\"\n q_type = \"Yes_No\"\n q_id = example['question_id']\n answer = example['answers']\n YES_NO_ANSWER = YES_NO_QUESTION[q_id]\n updated_example = get_pred(q_id,q_type,answer,YES_NO_ANSWER)\n writer.write(json.dumps(updated_example, ensure_ascii=False))\n writer.write('\\n')\n writer.close()\n\n\ndef build_answer_rank_dev(search_pre=\"F:\\\\baidu_raw_data\\search_nbest_predictions.json\",zhidao_pre=\"F:\\\\baidu_raw_data\\zhidao_nbest_predictions.json\",search_dev=\"F:\\\\baidu_raw_data\\dev_preprocessed\\dev_preprocessed\\devset\\\\search.dev.json\",zhidao_dev=\"F:\\\\baidu_raw_data\\dev_preprocessed\\dev_preprocessed\\devset\\zhidao.dev.json\"):\n\n out_path = \"F:\\\\baidu_raw_data\\dev_answer_rerank_train.json\"\n out_path1 = \"F:\\\\baidu_raw_data\\dev_answer_rerank_test.json\"\n cnt = 0\n with open(search_pre,encoding = 'utf-8') as f:\n data = json.load(f)\n ids = list(int(i) for i in data.keys())\n writer = open(out_path,'w',encoding='utf-8')\n writer1 = open(out_path1, 'w', encoding='utf-8')\n with open(search_dev,encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n q_id = example['question_id']\n q_type = example['question_type']\n question = example['question']\n answers = data[str(q_id)]\n example = {\n \"source\": \"search\",\n \"question_id\": q_id,\n \"question_type\": q_type,\n \"question\":question,\n \"answers\": answers,\n }\n if cnt % 10 ==0 :\n writer1.write(json.dumps(example, ensure_ascii=False))\n writer1.write('\\n')\n else:\n writer.write(json.dumps(example,ensure_ascii=False))\n writer.write('\\n')\n cnt+=1\n with open(zhidao_pre, encoding='utf-8') as f:\n data = json.load(f)\n ids = list(int(i) for i in data.keys())\n with open(zhidao_dev, encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n q_id = example['question_id']\n q_type = example['question_type']\n question = example['question']\n answers = data[str(q_id)]\n example = {\n \"source\": \"zhidao\",\n \"question_id\": q_id,\n \"question_type\": q_type,\n \"question\": question,\n \"answers\": answers\n }\n if cnt % 10 == 0:\n writer1.write(json.dumps(example, ensure_ascii=False))\n writer1.write('\\n')\n else:\n writer.write(json.dumps(example, ensure_ascii=False))\n writer.write('\\n')\n cnt+=1\n writer.close()\n writer1.close()\n\ndef build_baidu_train_v2(source_zhidao=\"F:\\\\baidu_raw_data\\\\train_preprocessed\\\\train_preprocessed\\\\trainset\\\\zhidao.train.json\",\n source_search=\"F:\\\\baidu_raw_data\\\\train_preprocessed\\\\train_preprocessed\\\\trainset\\\\search.train.json\",\n lhy_zhidao=\"F:\\Baidu_train\\lhy_train_zhidao.json\",\n lhy_search=\"F:\\Baidu_train\\lhy_train_search.json\",\n output=\"F:\\Baidu_train\\\\baidu_train_v22.json\"):\n\n# question, question_id, doc_tokens, fake_answer, answer_span,is_impossible:true,false\n def get_train(question,question_id,doc_tokens,fake_answer,answer_span,is_impossible,source):\n return{\n \"source\": source,\n \"question\":question,\n \"question_id\": question_id,\n \"doc_tokens\":doc_tokens,\n \"fake_answer\": fake_answer,\n \"answer_span\":answer_span,\n \"is_impossible\":is_impossible,\n }\n writer = open(output,\"w\",encoding='utf-8')\n zhidao_dict = {}\n id = []\n with open(lhy_zhidao,\"r\", encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n qas_id = example['question_id']\n zhidao_dict[int(qas_id)] = {\"question\":example['question'],\n \"doc_tokens\":example['doc_tokens'],\n \"answer_span\":example['answer_span'],\n \"fake_answer\":example['fake_answer']\n }\n id = list(zhidao_dict.keys())\n\n\n all_count = 0\n no_id = 0\n one_doc = 0\n useful_count = 0\n no_doc =0\n with open(source_zhidao,'r', encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n all_count +=1\n if int(example['question_id']) not in id:\n no_id+=1\n continue\n try:\n assert len(example[\"documents\"]) > 1\n except AssertionError:\n one_doc+=1\n # print(q_id)\n continue\n\n q_id = int(example['question_id'])\n question = example['question']\n fake_answer = example['fake_answers']\n assert fake_answer == zhidao_dict[q_id]['fake_answer']\n\n ans_doc = int(example['answer_docs'][0])\n for i in range(len(example['documents'])-1,-1,-1):\n doc_tokens = []\n if i == ans_doc:\n continue\n if example['documents'][i]['is_selected'] == \"true\":\n continue\n for para in example['documents'][i]['segmented_paragraphs']:\n doc_tokens.extend(para)\n break\n assert doc_tokens\n true_example = get_train(question, str(q_id) + \"_0\", zhidao_dict[q_id][\"doc_tokens\"], fake_answer, zhidao_dict[q_id][\"answer_span\"], \"false\", \"zhidao\")\n false_example = get_train(question,str(q_id)+\"_1\",doc_tokens,\"\",\"\",\"true\",\"zhidao\")\n writer.write(json.dumps(true_example,ensure_ascii=False))\n writer.write('\\n')\n writer.write(json.dumps(false_example,ensure_ascii=False))\n writer.write(\"\\n\")\n useful_count+=1\n\n search_dict = {}\n id = []\n with open(lhy_search,\"r\", encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n qas_id = example['question_id']\n search_dict[int(qas_id)] = {\"question\":example['question'],\n \"doc_tokens\":example['doc_tokens'],\n \"answer_span\":example['answer_span'],\n \"fake_answer\":example['fake_answer']\n }\n id = list(search_dict.keys())\n\n with open(source_search,'r', encoding='utf-8') as reader:\n for line in reader:\n all_count +=1\n example = json.loads(line)\n\n if int(example['question_id']) not in id:\n no_id+=1\n continue\n try:\n assert len(example[\"documents\"]) > 1\n except AssertionError:\n # print(q_id)\n one_doc+=1\n continue\n q_id = int(example['question_id'])\n question = example['question']\n fake_answer = example['fake_answers']\n assert fake_answer == search_dict[q_id]['fake_answer']\n ans_doc = int(example['answer_docs'][0])\n\n\n for i in range(len(example['documents'])-1,-1,-1):\n doc_tokens = []\n if i == ans_doc:\n continue\n if example['documents'][i]['is_selected'] == \"true\":\n continue\n if len(example['documents'][i]['segmented_paragraphs'][0])==0:\n continue\n for para in example['documents'][i]['segmented_paragraphs']:\n doc_tokens.extend(para)\n if doc_tokens ==[]:\n no_doc+=1\n print(q_id)\n continue\n true_example = get_train(question, str(q_id) + \"_0\", search_dict[q_id][\"doc_tokens\"], fake_answer,\n search_dict[q_id][\"answer_span\"], \"false\", \"search\")\n false_example = get_train(question,str(q_id)+\"_1\",doc_tokens,\"\",\"\",\"true\",\"search\")\n\n\n writer.write(json.dumps(true_example,ensure_ascii=False))\n writer.write('\\n')\n writer.write(json.dumps(false_example,ensure_ascii=False))\n writer.write(\"\\n\")\n useful_count+=1\n\n print(all_count)\n print(no_id)\n print(one_doc)\n print(no_doc)\n print(useful_count)\n writer.close()\n\n\ndef build_dev_v2(source_zhidao=\"F:\\\\baidu_raw_data\\dev_preprocessed\\dev_preprocessed\\devset\\zhidao.dev.json\",\n source_search=\"F:\\\\baidu_raw_data\\dev_preprocessed\\dev_preprocessed\\devset\\search.dev.json\",\n out=\"F:\\Baidu_train\\\\dev_v2.json\"):\n def get_dev(q_id,question,doc_tokens):\n return{\n 'question_id':q_id,\n \"question\":question,\n \"doc_tokens\":doc_tokens\n }\n writer = open(out,'w',encoding='utf-8')\n with open(source_zhidao,'r', encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n\n q_id = int(example['question_id'])\n question = example['question']\n for i in range(len(example['documents'])):\n doc_tokens = []\n for para in example['documents'][i]['segmented_paragraphs']:\n doc_tokens.extend(para)\n dev_example = get_dev(str(q_id)+'_'+str(i),question,doc_tokens)\n writer.write(json.dumps(dev_example,ensure_ascii=False))\n writer.write('\\n')\n\n with open(source_search,'r', encoding='utf-8') as reader:\n for line in reader:\n example = json.loads(line)\n\n q_id = int(example['question_id'])\n question = example['question']\n\n for i in range(len(example['documents'])):\n doc_tokens = []\n for para in example['documents'][i]['segmented_paragraphs']:\n doc_tokens.extend(para)\n dev_example = get_dev(str(q_id)+'_'+str(i),question,doc_tokens)\n\n writer.write(json.dumps(dev_example,ensure_ascii=False))\n writer.write('\\n')\n\ndef filter_top_doc_index(null_odd=\"C:\\\\Users\\workstation\\Desktop\\\\null_odds.json\",\n output =\"C:\\\\Users\\workstation\\Desktop\\\\id_dev_search.json\"):\n with open(null_odd,'r',encoding='utf-8') as f:\n data = json.load(f)\n ids = list(data.keys())\n raw_id ={}\n for id in ids:\n if id[:-2] not in raw_id.keys():\n raw_id[id[:-2]] = []\n\n for id in list(raw_id.keys()):\n odds =[]\n for i in range(5):\n if id+'_'+str(i) in ids:\n odds.append(data[id+'_'+str(i)])\n raw_id[id]=odds.index(max(odds))\n\n new_ids = list(raw_id.keys())\n writer = open(output,'w',encoding='utf-8')\n writer.write(json.dumps(raw_id,indent=4))\n","sub_path":"data/Data_process.py","file_name":"Data_process.py","file_ext":"py","file_size_in_byte":18237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"576927255","text":"import matplotlib.pyplot as plt\r\n\r\nARROW_ARGS = dict(arrowstyle=\"<-\")\r\nSTART_AXIS = 0.1\r\nEND_AXIS = 0.9\r\nAXIS_DISTANCE = END_AXIS - START_AXIS\r\nDECISION_NODE = dict(boxstyle='sawtooth', fc='#cab3f0')\r\nLEAF_NODE = dict(boxstyle='round4', fc='#c8dcc8')\r\n\r\n\r\nclass TreePlot:\r\n def __init__(self):\r\n self.ax1 = plt.subplot(1, 1, 1, frameon=False)\r\n pass\r\n\r\n def plotTree(self, tree):\r\n if tree.root is None:\r\n return\r\n\r\n startY = END_AXIS\r\n treeHeight = tree.getHeight()\r\n distanceY = AXIS_DISTANCE\r\n if treeHeight > 1:\r\n distanceY = AXIS_DISTANCE / (tree.getHeight() - 1)\r\n startX = START_AXIS\r\n endX = END_AXIS\r\n\r\n self.plotTreeNode(tree.root, startX, endX, startY, distanceY)\r\n plt.show()\r\n\r\n def plotTreeNode(self, treeNode, startX, endX, startY, distanceY, **kwargs):\r\n nodeStyle = LEAF_NODE if treeNode.isLeaf() else DECISION_NODE\r\n\r\n centerPt = ((endX - startX) / 2 + startX, startY)\r\n parentPt = kwargs.get('parentPt', centerPt)\r\n edgeLabel = kwargs.get('edgeLabel', None)\r\n\r\n self.plotNode(treeNode.label, centerPt, parentPt, nodeStyle)\r\n if edgeLabel is not None:\r\n self.plotText(edgeLabel, centerPt, parentPt)\r\n\r\n childrenCount = len(treeNode.children)\r\n if childrenCount == 1:\r\n distanceX = 0\r\n startX = endX = centerPt[0]\r\n else:\r\n distanceX = endX - startX\r\n startY -= distanceY\r\n\r\n totalWidth = treeNode.getWidth()\r\n for childEdgeLabel, childNode in treeNode.children.items():\r\n childWidth = childNode.getWidth()\r\n endX = startX + distanceX * childWidth / totalWidth\r\n\r\n self.plotTreeNode(childNode, startX, endX, startY, distanceY,\r\n parentPt=centerPt, edgeLabel=childEdgeLabel)\r\n startX = endX\r\n\r\n def plotNode(self, nodeTxt, centerPt, parentPt, nodeType):\r\n self.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',\r\n xytext=centerPt, textcoords='axes fraction',\r\n va='center', ha='center', bbox=nodeType, arrowprops=ARROW_ARGS)\r\n\r\n def plotText(self, text, centerPt, parentPt):\r\n xMid = (parentPt[0] + centerPt[0]) / 2.0\r\n yMid = (parentPt[1] + centerPt[1]) / 2.0\r\n self.ax1.text(xMid, yMid, text)\r\n","sub_path":"lesson-3/lesson3_src/common/treeplot.py","file_name":"treeplot.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"33839336","text":"import struct\nfrom struct import unpack\nimport numpy as np\nimport urllib.request\nfrom pathlib import Path\nfrom itertools import chain\n\nnp.random.seed(42)\n\n\ndef unpack_drawing(file_handle):\n # Skip key_id: 8, countrycode: 2, recognized: 1, timestamp: 4 = 15\n file_handle.read(15)\n (n_strokes,) = unpack(\"H\", file_handle.read(2))\n\n N = 0\n for i in range(n_strokes):\n (n_points,) = unpack(\"H\", file_handle.read(2))\n N += n_points\n file_handle.read(2 * n_points)\n\n return N\n\n\ndef unpack_drawings(filename):\n with open(filename, \"rb\") as f:\n while True:\n try:\n yield unpack_drawing(f)\n except struct.error:\n break\n\n\nurllib.request.urlretrieve(\n \"https://raw.githubusercontent.com/cs-deep-quickdraw/notebooks/master/100_classes.txt\",\n \"100_classes.txt\",\n)\n\n# Create data dir\nPath(\"./data\").mkdir(exist_ok=True)\n\nf = open(\"100_classes.txt\", \"r\")\n# And for reading use\nclasses = [cls.strip() for cls in f.readlines()][:15]\nf.close()\n\n\ndef download(classes):\n base = \"https://storage.googleapis.com/quickdraw_dataset/full/binary/\"\n for i, c in enumerate(classes):\n cls_url = c.replace(\"_\", \"%20\")\n path = base + cls_url + \".bin\"\n print((1 + i) / len(classes), c, path)\n urllib.request.urlretrieve(path, \"data/\" + c + \".bin\")\n\n\ndownload(classes)\n\n\ni_drawings = chain(*[unpack_drawings(f\"data/{cls}.bin\") for cls in classes])\n\nsizes = [size for size in i_drawings]\n\nprint(\n np.mean(sizes),\n np.percentile(sizes, 90),\n np.percentile(sizes, 95),\n np.percentile(sizes, 99),\n)\n","sub_path":"strokes_stats.py","file_name":"strokes_stats.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"604974255","text":"t = int(input())\nfor i in range(t):\n n, m = map(int,input().split())\n bi = list(reversed(bin(m)))\n #print(bi)\n for j in range(len(bi)-1):\n\n if j >= n:\n print(\"#\",i+1,\" ON\", sep='')\n break\n\n if bi[j] == '0':\n #print(\"#\",i,\" OFF\", sep='')\n break\n\n if j < n:\n print(\"#\",i+1,\" OFF\", sep='')\n ","sub_path":"SWEA/SWEA_10726.py","file_name":"SWEA_10726.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"526435965","text":"\"\"\"\nTwitInMyFace\n \nAuthors:\n Steven Tan\n Jason Tran\n \n#### Important Note ######\nThis file contains functions that are run by the Driver_program.py. Without the main program, this code will not run.\n\"\"\"\n\nimport unittest\nimport io\nimport random\n\n\n######################### Helper Functions ####################################\ndef nodes_names(lst: list) -> list:\n '''Convert a list of nodes to a list of names of friends. Return the list\n of name of friends.'''\n \n result = []\n for node in lst:\n result.append(node.get_name())\n return result\n\n\ndef nodes_emails(lst: list) -> list:\n '''Convert a list of nodes to a list of emails associated with each\n node. Return the list of emails'''\n \n result = []\n for node in lst:\n result.append(node.get_email())\n return result\n\n\ndef list_to_string(lst: list) -> str:\n \"\"\" \n Sorts the list and the converts the sorted list of strings into a \n single string. Return the string.\n \"\"\"\n \n lst.sort()\n output = ' '.join(lst)\n return output \n\n\ndef construct_network(file: 'file to be read') -> 'SocialNetwork':\n \"\"\"\n Returns a SocialNetwork object given a file.\n \"\"\"\n network = SocialNetwork()\n network.load_from_file(file)\n return network\n \n \n######################### Exception Class #####################################\nclass EmptyFileError(Exception):\n pass\n\n\n######################### Node Class ##########################################\nclass Node(object):\n '''Node object that contains a person's name, email, school and friends.'''\n def __init__(self, name: str, email: str, schools: str=None, \n friends: str=None):\n '''Initializes the Node object containing a person's name, \n email, school(s) and friend(s) where school(s) and friend(s)\n can be None'''\n \n self._name = name \n self._email = email \n self._schools = []\n if schools:\n for school in schools.split(','):\n self._schools.append(school) \n self._friends = []\n if friends:\n for friend in friends.split(','):\n self._friends.append(friend)\n \n def get_email(self) -> str:\n return self._email\n \n def get_name(self) -> str:\n return self._name\n \n def get_friends(self) -> list:\n return self._friends\n \n def get_schools(self) -> list:\n return self._schools\n\n\n######################### SocialNetwork Class #################################\nclass SocialNetwork(object):\n def __init__(self):\n '''Initializes the SocialNetwork class which contains a map of graph\n of nodes in the form of a dictionary {nodes: list of nodes}\n self._network, a list of emails self._emails and a list of nodes that \n corresponds to the list self._emails.'''\n self._network = {}\n self._emails = []\n self._nodes = []\n \n ############################# Helper Methods #############################\n def convert_to_lists(self, file: 'file to be read') -> None:\n '''Modify self._emails so that it contains all the emails from the \n file and modify self._nodes into a list of nodes that are associated\n with each email. No duplicates may exist in both lists.'''\n \n if isinstance(file, str):\n opened_file = open(file, 'r')\n else:\n opened_file = file\n for line in opened_file:\n if not line.strip():\n continue\n line = line.strip()\n # The first element of two_elements list is the name of person.\n two_elements = line.split('<')\n name = two_elements[0]\n # First element of two_sub_elements list is person's email\n # and the second element is person's friends as a string.\n two_sub_elements = two_elements[1].split('>(')\n email = two_sub_elements[0]\n rest = two_sub_elements[1].split('):')\n schools = rest[0]\n friends = rest[1]\n self._emails.append(email)\n self._nodes.append(Node(name, email, schools, friends))\n \n def email_index(self: 'SocialNetwork', email: str) -> int:\n '''Return the index of the email in the list self._emails'''\n \n return self._emails.index(email)\n \n def get_node(self: 'SocialNetwork', idx: int) -> 'Node':\n '''Return the node in self._nodes at given index idx.'''\n \n return self._nodes[idx]\n \n def email_to_name(self: 'SocialNetwork', lst: list) -> list:\n \"\"\"\n Return a list of the names of people which corresponds to \n the list of given emails.\n \"\"\"\n \n result = []\n for email in lst:\n idx = self.email_index(email)\n result.append(self._nodes[idx].get_name())\n return result\n\n def find_node_by_email(self: 'SocialNetwork', email: str) -> 'Node':\n \"\"\"\n Return the node associated with the email address email.\n \"\"\"\n found_idx = self.email_index(email)\n return self.get_node(found_idx) \n \n def emails_to_node(self: 'SocialNetwork', lst: list) -> list:\n '''Convert a list of emails lst to a list of nodes associated with each\n email. Return the list.'''\n \n result = []\n for email in lst:\n node = self.find_node_by_email(email)\n result.append(node)\n return result\n \n def read_from_file(self: 'SocialNetwork', file: 'file to be read') -> None:\n \"\"\" Reads the file given and constructs a dictionary of everyone\n If one person lists someone as their friend, but not the other way\n around, we'll make them both considered friends with each other.\n \"\"\"\n \n self.convert_to_lists(file)\n if len(self._emails) == 0:\n raise EmptyFileError() \n # Construct the dictionary of everyone.\n # Node of person: node of person's friends\n for node in self._nodes:\n list_friends = node.get_friends()\n friends_nodes = []\n for email in list_friends:\n idx = self.email_index(email)\n friends_nodes.append(self._nodes[idx])\n for person in self._network:\n i = self.email_index(person.get_email())\n item = self._nodes[i]\n if (node in self._network[person]) and (item not in \n friends_nodes):\n friends_nodes.append(item)\n self._network[node] = friends_nodes\n \n def people_with_degree_list(self, x: str, d: int) -> list:\n \"\"\"\n Returns a list of emails that corresponds to every person within \n 'd' degrees from person x.\n \"\"\"\n list_of_people_with_seperation = []\n \n for i in range(len(self._emails)):\n depth = self.degree_between(x, self._emails[i])\n if depth == int(d):\n list_of_people_with_seperation.append(self._emails[i])\n \n return list_of_people_with_seperation \n \n def mutual_friends_list(self, x: str, y: str) -> list:\n \"\"\"\n Returns a list of names of people who are mutual friends with person\n x and person y.\n \"\"\"\n \n node1 = self.find_node_by_email(x)\n node2 = self.find_node_by_email(y)\n lst_1 = node1.get_friends()\n lst_2 = node2.get_friends()\n lst_1_friends = self.email_to_name(lst_1)\n lst_2_friends = self.email_to_name(lst_2)\n set_1 = set(lst_1_friends)\n set_2 = set(lst_2_friends)\n # Find the emails that appear in both set_1 and set_2.\n intersect = set.intersection(set_1, set_2)\n result_lst = list(intersect)\n result_lst.sort() \n return result_lst \n \n def get_people_within_degrees(self: 'SocialNetwork', x: str, \n d: int) -> list:\n \"\"\"\n Returns a list of emails within a degree of separation of 'd' \n from person x.\n \"\"\"\n if int(d) <= 0:\n return []\n lst = self.people_with_degree_list(x, int(d))\n for i in range(1, int(d)):\n lst.extend(self.people_with_degree_list(x, int(d) - i))\n return lst\n \n ############################## Main Methods ##############################\n def load_from_file(self: 'SocialNetwork', file: 'file to be read') -> None:\n \"\"\"\n Retrieves data from file and puts the data in \n self._network in the form of a dictionary. The dictionary format will\n be {node: list of nodes} where each key of the dictionary is the node\n of each person in the file and the value associated with each key is\n the list of nodes that correspond to the person's friends.\n \"\"\"\n \n # Handles the exception where the file is empty.\n try:\n self.read_from_file(file)\n except EmptyFileError:\n print('The File Is Empty')\n # Ensure each friendship made is mutual, i.e A purports B is a friend,\n # then A will automatically be listed as B's friend.\n for key in self._network:\n for item in self._network:\n if item != key:\n if (key in self._network[item]) and (item not in \n self._network[key]):\n self._network[key].append(item)\n # Update the attribute _friends for each node in the dictionary, \n # if there is one. \n for key in self._network:\n if (self._network[key] == key.get_friends()):\n pass\n else:\n key._friends[:] = self._network[key]\n # Do the same for the nodes in the list self._nodes\n email = key.get_email()\n idx = self.email_index(email)\n lst = nodes_emails(self._network[key])\n self._nodes[idx]._friends[:] = lst\n \n def friends(self: 'SocialNetwork', email: str) -> str:\n \"\"\"\n Return a string that contains the names of every friend of the\n person that has the email email.\n \"\"\"\n \n idx = self.email_index(email)\n lst_nodes = self._network[self._nodes[idx]]\n lst_friends = nodes_names(lst_nodes)\n output = list_to_string(lst_friends)\n return output\n\n def degree_between(self: \"SocialNetwork\", x: str, y: str) -> int:\n \"\"\"\n Return the degree of separation between person x and person y \n (where people are specified by their e-mail address). \n In the network graph, the degree of separation between x and y \n corresponds to the number of edges on the shortest path between x \n and y. Return inf if no path is found between x and y.\n \"\"\"\n \n count = 0\n # lst used to keep track of emails already looked at\n lst = []\n to_pass_through = []\n # temp_list stores all the friends of nth iteration email \n # to be used for later\n temp_list = []\n # hold_values takes temp's contents and puts back into to_pass_through\n hold_values = []\n if y == x:\n return count\n # start off we use the initial email, which is [[email_of_x]]\n to_pass_through.append([x])\n while to_pass_through != [[]]:\n temp_list[:] = []\n emails = to_pass_through.pop(0) \n for email in emails:\n # Do not traverse through these nodes\n lst.append(email)\n for email in emails:\n cur_node = self.find_node_by_email(email)\n friends = cur_node.get_friends()\n if cur_node.get_email() == y:\n return count\n for friend in friends:\n if friend not in lst:\n temp_list.append(friend)\n # replace hold_values with the contents of temp list\n hold_values[:] = temp_list\n # to_pass_through is [['email1'...]] or [[]] if we checked\n # all friends possible already\n to_pass_through[:] = [hold_values] \n count = count + 1\n return float('inf')\n \n def people_with_degree(self, x: str, d: int) -> str:\n \"\"\"\n Return a string that contains the names of every person separated from \n person x by exactly d degrees of separation(where x is an \n e-mail address). The names will be sorted in an alphabetical order. \n \"\"\"\n \n lst_email = self.people_with_degree_list(x, int(d))\n lst_people = self.email_to_name(lst_email)\n output = list_to_string(lst_people)\n return output\n \n def mutual_friends(self, x: str, y: str) -> str:\n \"\"\"\n Return a string that contains the names of people who are friends with \n person x and person y where both parameters are the emails to both\n persons respectively. The names are sorted in alphabetical order. \n \"\"\"\n \n lst = self.mutual_friends_list(x, y)\n output = list_to_string(lst)\n return output\n \n def likely_friends(self, person: str) -> str:\n \"\"\"\n Return a string that contains the names of missing friends for a\n person by listing the likeliest missing friends where \n x is the person's email address. \n \"\"\"\n \n # Max mutual will start as 1 because if it's 0, then it will assume\n # that since x has zero mutual friends with y, we'll say that y is a\n # likely candidate, even though x probably doesn't know y. By putting\n # max_mutual = 1, we ensure that you have to at least have 1 friend in\n # common.\n max_mutual = 1\n missing_friends = []\n visited = []\n visited.append(person)\n node = self.find_node_by_email(person)\n for friend in node.get_friends():\n visited.append(friend)\n for i in range(len(self._emails)):\n # Search through every email that's avaliable in the graph\n if self._emails[i] in visited:\n continue\n # list of people who have mutual friends with current person\n lst_mutual = self.mutual_friends_list(person, self._emails[i])\n num_mutual = len(lst_mutual)\n # If the amount of mutual friends this person has with the other\n # Exceeds the current friend that has a lot of mutual friends\n # with the person, then we will replace the existing max with the\n # new candidate, if they're equal we'll add those two people.\n if num_mutual > max_mutual:\n max_mutual = num_mutual\n email = self._emails[i]\n missing_friends[:] = [email]\n elif num_mutual == max_mutual:\n missing_friends.append(self._emails[i])\n result_lst = self.email_to_name(missing_friends)\n result = list_to_string(result_lst)\n return result\n \n def classmates(self: 'SocialNetwork', x: str, d: int) -> str:\n \"\"\"\n Return a string that contains the names of every person within \n d degrees of separation of a person x who went to the \n same school as the person x and x is an email address of the person. \n \"\"\"\n \n classmates = []\n x_node = self.find_node_by_email(x)\n lst_emails = self.get_people_within_degrees(x, int(d))\n lst_nodes = self.emails_to_node(lst_emails)\n # Check every node in lst_nodes to see if any person went\n # to the same school as person x.\n for node in lst_nodes:\n for school in node.get_schools():\n # If the person is not already in the list classmates and \n # go to the same schooll as x, then append the person to\n # classmates.\n if school in x_node.get_schools() and \\\n node.get_name() not in classmates:\n classmates.append(node.get_name())\n result = list_to_string(classmates)\n return result\n \n\n########################### Unittest Test Cases ###############################\nclass TestDegree(unittest.TestCase):\n \n def test_one_person_no_friend(self: 'TestDegree') -> None:\n \"\"\"\n One person in the graph. Test to see if the degree between the start\n and itself, is zero(0).\n \"\"\"\n file = io.StringIO('person 1(Uni of Toronto): \\n')\n network = construct_network(file)\n input_val = network.degree_between('one@toronto.ca', 'one@toronto.ca')\n expected_output = 0\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_two_people_all_friends(self: 'TestDegree') -> None:\n \"\"\"\n Two Nodes in the graph, both friends with each other. Test to see if\n the degree between the two is 1.\n \"\"\"\n file = io.StringIO('A Kirby(Uni of Toronto):'\n 'metaknight@toronto.ca\\n'\n \n 'M Knight(Uni of Toronto):'\n 'kirby@toronto.ca\\n')\n network = construct_network(file)\n input_val = network.degree_between('kirby@toronto.ca',\n 'metaknight@toronto.ca')\n expected_output = 1\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_triangle_shaped_graph(self: 'TestDegree') -> None:\n \"\"\"\n A graph with 3 nodes are generated. Every node in the graph is\n connected to each other.\n \"\"\"\n file = io.StringIO('Kyon(Uni of Toronto):'\n 'Haruhi@toronto.ca\\n'\n \n 'Suzumiya Haruhi(Uni of Toronto):'\n 'YukiN@toronto.ca\\n'\n \n 'Nagato Yuki(Uni of Toronto):'\n 'kyon@toronto.ca\\n')\n network = construct_network(file)\n input_val = network.degree_between('kyon@toronto.ca',\n 'Haruhi@toronto.ca')\n expected_output = 1\n self.assertEqual(input_val, expected_output, 'Wrong degree between') \n \n def test_two_people_no_path(self: 'TestDegree') -> None:\n \"\"\"\n Two Nodes in the graph, testing degree_between one node and other,\n with no path in between the nodes. Test to see if it returns inf\n \"\"\"\n file = io.StringIO('A Kirby(Uni of Toronto): \\n'\n 'M Knight(Uni of Toronto): \\n')\n network = construct_network(file)\n input_val = network.degree_between('kirby@toronto.ca',\n 'metaknight@toronto.ca')\n expected_output = float('inf')\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_one_friend_multiple_path_length(self: 'TestDegree') -> None:\n \"\"\"\n Six Nodes in the graph.\n Tests to see that degree of one node to another takes the shortest\n path. First node only has one path then branches off \n converging to target.\n \"\"\"\n file = io.StringIO('C Falcon'\n '(Uni of Toronto):'\n 'FZero@toronto.ca\\n'\n \n 'F Zero(Uni of Toronto):'\n 'kirby@toronto.ca,finn@toronto.ca\\n'\n \n 'A Kirby(Uni of Toronto):'\n 'FZero@toronto.ca,king@princess.ca\\n'\n \n 'Finn(Uni of Toronto):'\n 'iceking@princess.ca\\n'\n \n 'Simon(Uni of Toronto):'\n 'king@princess.ca,finn@toronto.ca\\n'\n \n 'king(Uni of Toronto): \\n')\n network = construct_network(file)\n input_val = network.degree_between('showmeyamoves@toronto.ca',\n 'king@princess.ca')\n expected_output = 3\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_one_path_one_friend(self: 'TestDegree') -> None:\n \"\"\"\n Seven Nodes in the graph. Everyone has at most 1 friend.\n Tests to see if it follows the path given.\n looks like: X-o-o-o-o-Y-o\n Where x is the start and y is the end\n \"\"\"\n file = io.StringIO('C Falcon'\n '(Uni of Toronto):'\n 'FZero@toronto.ca\\n'\n \n 'F Zero(Uni of Toronto):'\n 'kirby@toronto.ca\\n'\n \n 'A Kirby(Uni of Toronto):'\n 'cooguy@toronto.ca\\n'\n \n 'Coo Guy(Uni of Toronto):'\n 'iceking@princess.ca\\n'\n \n 'Simon(Uni of Toronto):'\n 'king@princess.ca\\n'\n \n 'king(Uni of Toronto):'\n 'meepo@geomancer.ca\\n'\n \n 'Meepo(Uni of Toronto): \\n')\n network = construct_network(file)\n input_val = network.degree_between('showmeyamoves@toronto.ca',\n 'king@princess.ca')\n expected_output = 5\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_multiple_friends_multiple_path_length(self: 'TestDegree') -> None:\n \"\"\"\n 10 nodes in graph. Every person has more than 3 friends\n Tests to see if degree between X and Y returns the shortest one.\n \"\"\"\n file = io.StringIO('C Falcon'\n '(Uni of Toronto):'\n 'FZero@toronto.ca,kirby@toronto.ca,'\n 'cooguy@toronto.ca\\n'\n \n 'F Zero(Uni of Toronto):'\n 'kirby@toronto.ca,showmeyamoves@toronto.ca,'\n 'meepo@geomancer.ca\\n'\n \n 'A Kirby(Uni of Toronto):'\n 'cooguy@toronto.ca,iceking@princess.ca,'\n 'king@princess.ca,meepo@geomancer.ca,'\n 'showmeyamoves@toronto.ca,FZero@toronto.ca\\n'\n \n 'Coo Guy(Uni of Toronto):'\n 'iceking@princess.ca,axe@axed.ca\\n'\n \n 'Simon(Uni of Toronto):'\n 'king@princess.ca,axe@axed.ca,'\n 'cooguy@toronto.ca,dk@dragon.ca\\n'\n \n 'king(Uni of Toronto):'\n 'meepo@geomancer.ca,dk@dragon.ca,'\n 'kirby@toronto.ca,iceking@princess.ca\\n'\n \n 'Meepo(Uni of Toronto):'\n 'dk@dragon.ca,king@princess.ca,kirby@toronto.ca,'\n 'FZero@toronto.ca\\n'\n \n 'axe(Uni of Toronto):'\n 'cooguy@toronto.ca,alistar@moo.ca,'\n 'iceking@princess.ca\\n'\n \n 'alistar(Uni of Toronto):'\n 'dk@dragon.ca,axe@axed.ca,iceking@princess.ca\\n'\n \n 'Knight Davian(Uni of Toronto):'\n 'alistar@moo.ca,meepo@geomancer.ca,'\n 'king@princess.ca,iceking@princess.ca\\n')\n network = construct_network(file)\n input_val = network.degree_between('showmeyamoves@toronto.ca',\n 'king@princess.ca')\n expected_output = 2\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n\n def test_a_lot_people_no_friends(self: 'TestDegree') -> None:\n \"\"\"\n 10 nodes in graph. No one is friends with one another\n target is not itself. Test to see if degree_between returns \n infinity with a large set.\n \"\"\"\n file = io.StringIO('C Falcon'\n '(Uni of Toronto): \\n'\n \n 'F Zero(Uni of Toronto): \\n'\n \n 'A Kirby(Uni of Toronto): \\n'\n \n 'Coo Guy(Uni of Toronto): \\n'\n \n 'Simon(Uni of Toronto): \\n'\n \n 'king(Uni of Toronto): \\n'\n \n 'Meepo(Uni of Toronto): \\n'\n \n 'axe(Uni of Toronto): \\n'\n \n 'alistar(Uni of Toronto): \\n'\n \n 'Knight Davian(Uni of Toronto): \\n')\n network = construct_network(file)\n input_val = network.degree_between('showmeyamoves@toronto.ca',\n 'king@princess.ca')\n expected_output = float('inf')\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_multiple_friends_same_path_length(self: 'TestDegree') -> None:\n \"\"\"\n A graph with 6 nodes are created. Then 2 specific nodes will be\n selected such that every path between these 2 nodes will yield\n the same number of edges.\n \"\"\"\n \n file = io.StringIO('A Dylan(Uni of Toronto):c@dra.net,'\n 'b@dra.net\\nB Ba():e@dra.net\\n'\n 'E Ea():z@dra.net\\nZ Za'\n '():d@dra.net\\nD Da():c@dra.net\\n'\n 'C Ca():')\n network = construct_network(file)\n input_val = network.degree_between('a@dra.net', 'z@dra.net')\n expected_output = 3\n self.assertEqual(input_val, expected_output, 'Wrong degree between') \n \n def test_multiple_friends_no_path(self: 'TestDegree') -> None:\n \"\"\"\n A graph with 7 nodes are created. Then 2 specific nodes will be\n selected such that no path exists between these two nodes.\n \"\"\"\n file = io.StringIO('A Dylan(Uni of Toronto):c@dra.net,'\n 'b@dra.net\\nB Ba():\\n'\n 'E Ea():z@dra.net\\nZ Za'\n '():d@dra.net\\nD Da():\\n'\n 'C Ca():\\nS Ta():')\n network = construct_network(file)\n input_val = network.degree_between('a@dra.net', 'z@dra.net')\n expected_output = float('inf')\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_multiple_friends_one_path(self: 'TestDegree') -> None:\n \"\"\"\n A graph with 9 nodes are created. Then 2 specific nodes will be \n selected such that only one path exists between the two nodes. \n Some paths will lead to a deadend. Test to see if even if it are \n deadends in the graph, degree_between can still find the path \n to target node from the beginning node.\n \"\"\"\n \n file = io.StringIO('A Dylan(Uni of Toronto):b@dra.net\\n'\n 'B Ba():c@dra.net,e@dra.net,g@dra.net\\n'\n 'C Ca():d@dra.net\\n'\n 'D Da():\\n'\n 'E Ea():f@dra.net\\n'\n 'F Fa():\\n'\n 'G Ga():h@dra.net,i@dra.net\\n'\n 'H Ha():\\n'\n 'I Ia():\\n')\n network = construct_network(file)\n input_val = network.degree_between('a@dra.net', 'i@dra.net')\n expected_output = 3\n self.assertEqual(input_val, expected_output, 'Wrong degree between') \n \n def test_one_person_with_friends_same_person(self: 'TestDegree') -> None:\n \"\"\"\n Graph contains 6 nodes. 5 nodes are connected to the same node. That \n same node is our target node. Test if the degree_between is still 0.\n \"\"\"\n \n file = io.StringIO('A Dylan(Uni of Toronto):\\n'\n 'B Ba():a@dra.net\\n'\n 'C Ca():a@dra.net\\n'\n 'D Da():a@dra.net\\n'\n 'E Ea():a@dra.net\\n'\n 'F Fa():a@dra.net\\n')\n network = construct_network(file)\n input_val = network.degree_between('a@dra.net', 'a@dra.net')\n expected_output = 0\n self.assertEqual(input_val, expected_output, 'Wrong degree between') \n \n def test_long_graph_multiple_routes(self: 'TestDegree') -> None:\n \"\"\"\n Graph with 20 are created. 2 specific nodes will be selected such that\n multiple paths exist between those 2 nodes.\n Test to see if the degree_between function can still find the shortest \n path.\n \"\"\"\n \n file = io.StringIO('A Dylan(Uni of Toronto):b@dra.net,'\n 'e@dra.net,f@dra.net\\n'\n 'B Ba():c@dra.net,g@dra.net\\n'\n 'C Ca():h@dra.net\\n'\n 'D Da():e@dra.net\\n'\n 'E Ea():i@dra.net\\n'\n 'F Fa():j@dra.net\\n,g@dra.net,i@dra.net'\n 'G Ga():k@dra.net\\n'\n 'H Ha():g@dra.net,l@dra.net\\n'\n 'I Ia():m@dra.net\\n'\n 'J Ja():k@dra.net,m@dra.net,n@dra.net\\n'\n 'K Ka():n@dra.net\\n'\n 'L La():k@dra.net,n@dra.net\\n'\n 'M Ma():n@dra.net\\n'\n 'N Na():\\n')\n network = construct_network(file)\n input_val = network.degree_between('a@dra.net', 'n@dra.net')\n expected_output = 3\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_starter_no_connected_nodes(self: 'TestDegree') -> None:\n \"\"\"\n Graph with 3 nodes, the starting node is not connected to any node\n The other 2 nodes along with the target node is connected to each other\n \"\"\"\n file = io.StringIO('Kyon(Uni of Toronto): \\n'\n \n 'Suzumiya Haruhi(Uni of Toronto):'\n 'YukiN@toronto.ca\\n'\n \n 'Nagato Yuki(Uni of Toronto):'\n 'Haruhi@toronto.ca\\n')\n network = construct_network(file)\n input_val = network.degree_between('kyon@toronto.ca',\n 'Haruhi@toronto.ca')\n expected_output = float('inf')\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n\n def test_starter_no_connected_nodes(self: 'TestDegree') -> None:\n \"\"\"\n Graph with 3 nodes, the starting node is connected to all nodes\n avaliable except for the target node.\n \"\"\"\n file = io.StringIO('Kyon(Uni of Toronto): \\n'\n \n 'Suzumiya Haruhi(Uni of Toronto):'\n 'YukiN@toronto.ca\\n'\n \n 'Nagato Yuki(Uni of Toronto):'\n 'Haruhi@toronto.ca\\n')\n network = construct_network(file)\n input_val = network.degree_between('Haruhi@toronto.ca',\n 'kyon@toronto.ca')\n expected_output = float('inf')\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n def test_275_people(self: 'TestDegree') -> None:\n \"\"\"\n Graph with 275 nodes are randomly generated. One node and node adjacent\n to that one node are selected. Test to see if degree_between is 1.\n \"\"\"\n \n lst = []\n lst_email = []\n alph = 'abcdefghijklmnopqrstuvwxyz'\n for i in range(275):\n string = ''\n last = ''\n for n in range(5):\n string += alph[random.randint(0, 25)]\n last += alph[random.randint(0, 25)]\n name = string + ' ' + last\n email = string + '@user.net'\n school = 'University of Kawaii'\n if lst_email:\n friends = lst_email[random.randint(0, len(lst_email) - 1)]\n else:\n friends = ''\n final = name + '<' + email + '>(' + school + '):' + friends + '\\n'\n if email not in lst_email:\n lst_email.append(email)\n lst.append(final)\n final_file = ''.join(lst)\n file = io.StringIO(final_file)\n network = construct_network(file)\n starting_email = network._emails[150]\n end_email = network.find_node_by_email(starting_email).get_friends()\n input_val = network.degree_between(starting_email, end_email[0])\n expected_output = 1\n self.assertEqual(input_val, expected_output, 'Wrong degree between')\n \n \n################################ Unittest end ################################# \nif __name__ == '__main__':\n unittest.main(exit=False)\n","sub_path":"Python graph practice/SocialNetwork.py","file_name":"SocialNetwork.py","file_ext":"py","file_size_in_byte":34838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"647407526","text":"import torch\nimport os\nimport sys\nimport pandas as pd\nimport pickle\nimport torch.nn as nn\nimport time\nimport nltk\nimport numpy\nfrom torchvision import transforms\nfrom dataLoader import getLoader\nfrom dataset.Vocabulary import Vocabulary\nfrom model.model import EncoderCNN, DecoderLSTM\nfrom torch.nn.utils.rnn import pack_padded_sequence\n\ndef idToWord(sentence):\n\ts = []\n\tfor wordID in sentence:\n\t\tword = vocabulary.idx2word[wordID]\n\t\ts.append(word)\n\t\tif word == '':\n\t\t\tbreak\n\treturn s\n\n#Setting device\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nchencherry = nltk.translate.bleu_score.SmoothingFunction()\npath = sys.path[0]\n\n#Hyperparameter\nencoder_path = os.path.join(path, 'trained', 'EncoderCNN', 'v12')\ndecoder_path = os.path.join(path, 'trained', 'DecoderLSTM', 'v12')\ntrained_encoder = os.path.join(encoder_path, 'encoder-20-final.ckpt')\ntrained_decoder = os.path.join(decoder_path, 'decoder-20-final.ckpt')\nvocabulary_path = os.path.join(path, 'dataset', 'vocab.pkl')\nimage_path = os.path.join(path, 'dataset', 'train_set')\ntitle_path = os.path.join(path, 'dataset', 'train_set.csv')\nval_image_path = os.path.join(path, 'dataset', 'val_set')\nval_title_path = os.path.join(path, 'dataset', 'val_set.csv')\nlogs_path = os.path.join(path, 'logs', 'v12')\nembedding_size = 512\nmomentum = 0.0001\nlearning_rate = 0.0001\nhidden_size = 1024\nnum_layers = 1\nresize = 224\nmax_length = 40\nbatch_size = 8\nnum_workers = 0\nnum_epochs = 26\nstep = 5\n\n#Create folders\nif not os.path.exists(encoder_path):\n\tos.makedirs(encoder_path)\nif not os.path.exists(decoder_path):\n\tos.makedirs(decoder_path)\nif not os.path.exists(logs_path):\n\tos.makedirs(logs_path)\n\n#Create trasforms\ntransforms = transforms.Compose([transforms.Resize(resize), transforms.RandomCrop(resize), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n#Load vocabulary\nwith open(vocabulary_path, 'rb') as f:\n\tvocabulary = pickle.load(f)\nprint('Vocabulary loaded. Size:', len(vocabulary))\n\n#Prepare product title list\ntrain_titles = pd.read_csv(title_path)\ntrain_titles = train_titles['title'].tolist()\nval_titles = pd.read_csv(val_title_path)\nval_titles = val_titles['title'].tolist()\n\n#Prepare data loader\ndata_loader = getLoader(image_path, train_titles, vocabulary, transforms, batch_size, True, num_workers)\nval_loader = getLoader(val_image_path, val_titles, vocabulary, transforms, batch_size, True, num_workers)\nbleu_train_loader = getLoader(image_path, train_titles, vocabulary, transforms, 1, False, num_workers)\nbleu_val_loader = getLoader(val_image_path, val_titles, vocabulary, transforms, 1, False, num_workers)\n\n#Create model\nencoder = EncoderCNN(embedding_size, momentum).to(device)\ndecoder = DecoderLSTM(embedding_size, hidden_size, len(vocabulary), num_layers, max_length).to(device)\n\nencoder.load_state_dict(torch.load(trained_encoder))\ndecoder.load_state_dict(torch.load(trained_decoder))\n\n#Configure optimizer\ncriterion = nn.CrossEntropyLoss()\nparams = list(decoder.parameters()) + list(encoder.parameters())\noptimizer = torch.optim.Adam(params, lr=learning_rate)\n\n#Training\ntotal_step = len(data_loader)\ntotal_val = len(val_loader)\ntotal_bleu_train = len(bleu_train_loader)\ntotal_bleu_val = len(bleu_val_loader)\n\nfor epoch in range(21,num_epochs):\n\tloss_train = 0\n\tloss_val = 0\n\tencoder.train()\n\tdecoder.train()\n\t\n\tprint('Start Train')\n\tfor i, (indexes, images, titles, lengths) in enumerate(data_loader):\n\n\t\timages = images.to(device)\n\t\ttitles = titles.to(device)\n\t\ttargets = pack_padded_sequence(titles, lengths, batch_first=True)[0]\n\n\t\tfeatures = encoder(images)\n\t\toutputs = decoder(features, titles, lengths)\n\n\t\tloss = criterion(outputs, targets)\n\t\tdecoder.zero_grad()\n\t\tencoder.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\t\tloss_train += loss.item() * images.size(0)\n\n\t\tif i % (len(data_loader)//4) == 0:\n\t\t\tprint('Epoch [{}/{}], Step [{}/{}], Train Loss: {:.4f}'.format(epoch, num_epochs, i, total_step, loss.item()))\n\t\t\n\ttorch.save(decoder.state_dict(), os.path.join(decoder_path, 'decoder-{}-final.ckpt'.format(epoch)))\n\ttorch.save(encoder.state_dict(), os.path.join(encoder_path, 'encoder-{}-final.ckpt'.format(epoch)))\n\n\twith open(os.path.join(logs_path, 'train_epoch_loss.txt'), 'a') as f:\n\t\tf.write(str(loss_train/len(train_titles)) + '\\n')\n\n\twith torch.no_grad():\n\t\tencoder.eval()\n\t\tdecoder.eval()\n\n\t\tprint('Start Validate')\n\t\tfor i, (indexes, images, titles, lengths) in enumerate(val_loader):\n\t\t\t\n\t\t\timages = images.to(device)\n\t\t\ttitles = titles.to(device)\n\t\t\ttargets = pack_padded_sequence(titles, lengths, batch_first=True)[0]\n\n\t\t\tfeatures = encoder(images)\n\t\t\toutputs = decoder(features, titles, lengths)\n\n\t\t\tloss = criterion(outputs, targets)\n\n\t\t\tloss_val += loss.item() * images.size(0)\n\n\t\t\tif i % (len(val_loader)//4) == 0:\n\t\t\t\tprint('Epoch [{}/{}], Step [{}/{}], Validation Loss: {:.4f}'.format(epoch, num_epochs, i, total_val, loss.item()))\n\n\t\twith open(os.path.join(logs_path, 'val_epoch_loss.txt'), 'a') as f:\n\t\t\tf.write(str(loss_val/len(val_titles)) + '\\n')\n\n\t\tprint('Epoch [{}/{}], Epoch Train Loss: {:.4f}, Epoch Validation Loss: {:.4f}'.format(epoch, num_epochs, loss_train/len(train_titles), loss_val/len(val_titles)))\n\n\t\tif epoch % step == 0:\n\t\t\tprint('Calculate BLEU Train')\n\t\t\tbleu1_train_score = 0\n\t\t\tfor i, (indexes, images, titles, lengths) in enumerate(bleu_train_loader):\n\n\t\t\t\timages = images.to(device)\n\t\t\t\t\n\t\t\t\tfeatures = encoder(images)\n\t\t\t\tsampled_ids = decoder.greedySearch(features)\n\n\t\t\t\tsampled_ids = sampled_ids[0].cpu().numpy()\n\n\t\t\t\ttitles = titles.detach().cpu().numpy()\n\t\t\t\tground_truth = []\n\t\t\t\tfor title in titles:\n\t\t\t\t\tground_truth.append(idToWord(title))\n\n\t\t\t\tgenerated = idToWord(sampled_ids)\n\n\t\t\t\ttemp_score = 0\n\t\t\t\tif len(generated) > 1:\n\t\t\t\t\ttemp_score = nltk.translate.bleu_score.sentence_bleu(ground_truth,generated,weights=(1., 0, 0, 0),smoothing_function=chencherry.method7)\n\t\t\t\tbleu1_train_score += temp_score\n\n\t\t\t\tif i % (len(bleu_train_loader)//4) == 0:\n\t\t\t\t\tprint('Epoch [{}/{}], Step [{}/{}], BLEU-1 Train: {:.4f}'.format(epoch, num_epochs, i, total_bleu_train, temp_score))\n\n\t\t\tavg_bleu1_train = bleu1_train_score/total_bleu_train\n\t\t\twith open(os.path.join(logs_path, 'train_epoch_bleu.txt'), 'a') as f:\n\t\t\t\tf.write(str(avg_bleu1_train) + '\\n')\n\n\t\t\tprint('Calculate BLEU Validation')\n\t\t\tbleu1_val_score = 0\n\t\t\tfor i, (indexes, images, titles, lengths) in enumerate(bleu_val_loader):\n\n\t\t\t\timages = images.to(device)\n\t\t\t\t\n\t\t\t\tfeatures = encoder(images)\n\t\t\t\tsampled_ids = decoder.greedySearch(features)\n\n\t\t\t\tsampled_ids = sampled_ids[0].cpu().numpy()\n\n\t\t\t\ttitles = titles.detach().cpu().numpy()\n\t\t\t\tground_truth = []\n\t\t\t\tfor title in titles:\n\t\t\t\t\tground_truth.append(idToWord(title))\n\n\t\t\t\tgenerated = idToWord(sampled_ids)\n\n\t\t\t\ttemp_score = 0\n\t\t\t\tif len(generated) > 1:\n\t\t\t\t\ttemp_score = nltk.translate.bleu_score.sentence_bleu(ground_truth,generated,weights=(1., 0, 0, 0),smoothing_function=chencherry.method7)\n\t\t\t\tbleu1_val_score += temp_score\n\n\t\t\t\tif i % (len(bleu_val_loader)//4) == 0:\n\t\t\t\t\tprint('Epoch [{}/{}], Step [{}/{}], BLEU-1 Validation: {:.4f}'.format(epoch, num_epochs, i, total_bleu_val, temp_score))\n\n\t\t\tavg_bleu1_val = bleu1_val_score/total_bleu_val\n\t\t\twith open(os.path.join(logs_path, 'val_epoch_bleu.txt'), 'a') as f:\n\t\t\t\tf.write(str(avg_bleu1_val) + '\\n')\n\n\t\t\tprint('Epoch [{}/{}], Epoch Train BLEU-1: {:.4f}, Epoch Validation BLEU-1: {:.4f}'.format(epoch, num_epochs, avg_bleu1_train, avg_bleu1_val))\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"158214230","text":"\n\"\"\"\nSVM Classifier for model 2 using VGG 19 features\nPaper: Ravi, Aravind, Harshwin Venugopal, Sruthy Paul, and Hamid R. Tizhoosh. \n\"A Dataset and Preliminary Results for Umpire Pose Detection Using SVM Classification of Deep Features.\" \narXiv preprint arXiv:1809.06217 (2018).\n\n\"\"\"\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeaveOneOut\nimport pickle\nimport time\n\nlayers_to_extract = [\"fc1\",\"fc2\"]\n\nlayer_num = 0\n\n#Loading the Features\nX1 = np.load(\"class_cricket\"+layers_to_extract[layer_num]+\"1vgg19_data.npy\")\nX2 = np.load(\"class_cricket\"+layers_to_extract[layer_num]+\"2vgg19_data.npy\")\nX3 = np.load(\"class_cricket\"+layers_to_extract[layer_num]+\"3vgg19_data.npy\")\nX4 = np.load(\"class_cricket\"+layers_to_extract[layer_num]+\"4vgg19_data.npy\")\nX5 = np.load(\"class_cricket\"+layers_to_extract[layer_num]+\"5vgg19_data.npy\")\n\n\n#Concatenate into single matrix\nX_data = np.append(X1,X2,axis=0)\nX_data = np.append(X_data,X3,axis=0)\nX_data = np.append(X_data,X4,axis=0)\nX_data = np.append(X_data,X5,axis=0)\n\n#Labels\nY_data = X_data[:,(X_data.shape[1]-1)]\n\n#Training Data\nX_data = X_data[:,0:(X_data.shape[1]-1)]\n\n#Train Test Split 80-20\nx_tr,x_ts,y_tr,y_ts = train_test_split(X_data, Y_data, test_size=0.2,random_state=157)\n\n#Classifier SVM Linear Kernel \nclf = LinearSVC(C=10)\n\nstart_time = time.time()\n\nclf = clf.fit(x_tr,y_tr)\npredictions_tr = (clf.predict(x_ts))\n\n#10-Fold Cross-validation Accuracy\nscores = cross_val_score(clf, x_tr, y_tr, cv=10)\nprint(layers_to_extract[layer_num])\nprint(\"Training Accuracy: %0.4f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n#Leave One Out or Jack-Knife Crossvalidation\nloo_train_acc=[]\nloo = LeaveOneOut()\nfor train_index, test_index in loo.split(x_tr):\n X_train, X_test = x_tr[train_index], x_tr[test_index]\n y_train, y_test = y_tr[train_index], y_tr[test_index]\n clf = clf.fit(X_train,y_train)\n predictions = (clf.predict(X_test))\n loo_train_acc.append(accuracy_score(y_test,predictions))\n\nloo_train_accuracy = np.asarray(loo_train_acc)\nprint(\"LOO Accuracy: %0.4f\" % loo_train_accuracy.mean())\n\n#20% Test Data Accuracy\ntest_acc = accuracy_score(y_ts,predictions_tr)\nprint(\"Test Accuracy: %0.4f\" % test_acc)\n\n#Save the PCA parameters and SVM Model\npickle.dump(clf, open('FER_vgg19fc2_model2net_ck_transfer_only_svm.sav', 'wb'))\n","sub_path":"Code/VGG19_Method/vgg19_classifier_model2.py","file_name":"vgg19_classifier_model2.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"166668351","text":"import socket\n\naddress = \"peering.nano.org\"\nport = 7075\n\nenum_network = {}\nfor i, network_id in enumerate(\n [\"network_test\", \"network_beta\", \"network_live\"], start=ord(\"A\")\n):\n enum_network[network_id] = i.to_bytes(1, byteorder=\"big\")\n\nenum_msgtype = {}\nfor i, msgtype in enumerate(\n [\n \"invalid\",\n \"not_a_type\",\n \"keepalive\",\n \"publish\",\n \"confirm_req\",\n \"confirm_ack\",\n \"bulk_pull\",\n \"bulk_push\",\n \"frontier_req\",\n \"bulk_pull_blocks\",\n \"node_id_handshake\",\n \"bulk_pull_account\",\n ]\n):\n enum_msgtype[msgtype] = i.to_bytes(1, byteorder=\"big\")\n\nenum_blocktype = {}\nfor i, blocktype in enumerate(\n [\"invalid\", \"not_a_block\", \"send\", \"receive\", \"open\", \"change\", \"state\"]\n):\n enum_blocktype[blocktype] = i.to_bytes(1, byteorder=\"big\")\n\nmagic = b\"R\"\nnetwork_id = enum_network[\"network_live\"]\nversion_max = (16).to_bytes(1, byteorder=\"big\")\nversion_using = (16).to_bytes(1, byteorder=\"big\")\nversion_min = (13).to_bytes(1, byteorder=\"big\")\nmessage_type = enum_msgtype[\"keepalive\"]\nextensions = (0x0000).to_bytes(2, byteorder=\"big\")\n# ~ extensions = (0xffff & 0x0001).to_bytes(2, byteorder='big')\n# ~ extensions = (0xffff & 0x0002).to_bytes(2, byteorder='big')\n# ~ extensions = ((0xffff & 0x0f00)>>8).to_bytes(2, byteorder='big')\n# ~ print(account_key('nano_3ooycog5ejbce9x7nmm5aueui18d1kpnd74gc4s67nid114c5bp4g9nowusy'))\n# ~ start = bytes.fromhex(\n# ~ 'd6be555c36452a61fa5a4e6346d9b800cb04ad45944e50b242d20b0004a1a6c2')\n# ~ age = bytes.fromhex('ffffffff')\n# ~ count = bytes.fromhex('ffffffff')\n# ~ body = start + age + count\npeer = bytes.fromhex(\"000000000000000000000000000000000000\")\nbody = peer\nfor i in range(7):\n body += peer\n\nsock = socket.socket(\n socket.AF_INET, socket.SOCK_DGRAM\n) # SOCK_DGRAM - UDP # SOCK_STREAM - TCP\n# ~ sock.bind(('', 7075))\n# ~ sock.connect((address, port))\nmsg = (\n magic\n + enum_network[\"network_live\"]\n + version_max\n + version_using\n + version_min\n + message_type\n + extensions\n + body\n)\n# ~ sock.send(msg)\nsock.sendto(msg, (address, port))\nprint(msg.hex())\nresponse = sock.recv(1024)\nprint(response.hex())\n","sub_path":"nanopy/peer.py","file_name":"peer.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"522026351","text":"import model1\n\nmodel_save_path1 = \"model/model.ckpt\"\nmodel_save_path2 = \"model/model2.ckpt\"\nmodel_save_path3 = \"model/model3.ckpt\"\nmodel_save_path4 = \"model/model4.ckpt\"\nmodel_save_path5 = \"model/model5.ckpt\"\nmodel_save_path6 = \"model/model6.ckpt\"\nmodel_save_path7 = \"model/model7.ckpt\"\n\n#Three of the first model\nresults1 = model1.LoadAndRun(model_save_path1)\n\n\nwith open(\"results/results.csv\", 'w') as file:\n file.write(\"ImageId,Label\\n\")\n for idx in range(len(results1)):\n pred1 = int(results1[idx])\n\n nums = np.zeros(10)\n nums[pred1] = nums[pred1] + 1 \n\n prediction = np.argmax(nums)\n\n file.write(str(idx + 1))\n file.write(\",\")\n file.write(str(prediction))\n file.write(\"\\n\")","sub_path":"CatVsDogs/CatVsDogs/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"65793582","text":"# Copyright (c) hoduchieu01\nclass Solution:\n def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:\n word_dict = defaultdict(list)\n for i, w in enumerate(words):\n if w in (word1, word2): \n word_dict[w].append(i)\n minDistance = float('inf')\n for i in word_dict[word1]:\n for j in word_dict[word2]:\n minDistance = min(minDistance, abs(i-j))\n return minDistance","sub_path":"interview/LeetCode/DecemberLeetCodingChallenge/Week1/Shortest_Word_Distance.py","file_name":"Shortest_Word_Distance.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"439466641","text":"from bot import Bot\nimport random\nfrom constants import *\n\n\nclass TJBotOld(Bot):\n def __init__(self):\n self.Dynamite = 0\n self.repeat_flag = False\n self.repeat_value = ''\n self.buffer = ['', '', '']\n\n def make_move(self, gamestate):\n\n self.check_4_repeat(gamestate)\n if self.repeat_flag:\n Move = TJBotOld.beat_const_bot(self)\n else:\n Move = TJBotOld.make_random_move(self)\n\n return Move\n\n def check_4_repeat(self, gamestate):\n length = len(gamestate[\"rounds\"])\n if length >= 1:\n # shift and fill in the the 3 item long list 'buffer'\n self.buffer[0] = self.buffer[1]\n self.buffer[1] = self.buffer[2]\n self.buffer[2] = gamestate[\"rounds\"][length - 1][\"p2\"]\n if self.buffer[0] == self.buffer[1] and self.buffer[0] == self.buffer[2]:\n self.repeat_flag = True\n self.repeat_value = self.buffer[2]\n else:\n self.repeat_flag = False\n\n def beat_const_bot(self):\n if self.repeat_value == 'R':\n Move = 'P'\n elif self.repeat_value == 'P':\n Move = 'S'\n elif self.repeat_value == 'S':\n Move = 'R'\n elif self.repeat_value == 'D':\n Move = 'W'\n else:\n Move = 'R'\n\n return Move\n\n def make_random_move(self):\n moveIndex = random.choice([0, 1, 2, 3, 4])\n if moveIndex == 4:\n self.Dynamite += 1\n\n if self.Dynamite >= NUM_DYNAMITE:\n moveIndex = random.choice([0, 1, 2, 3])\n\n Move = VALID_MOVES[moveIndex]\n return Move\n","sub_path":"tjbotold.py","file_name":"tjbotold.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"40514607","text":"from django import forms\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.html import mark_safe\n\nfrom .models import Thing\n\n\ndef test_misc(request):\n return render(request, \"django_functest/tests/test_misc.html\",\n {'name': request.session.get('name', None)})\n\n\nclass ThingForm(forms.ModelForm):\n def __init__(self, add_spacers=False, **kwargs):\n super(ThingForm, self).__init__(**kwargs)\n self.add_spacers = add_spacers\n\n def as_p(self):\n retval = super(ThingForm, self).as_p()\n if self.add_spacers:\n # Hack to help test interacting with elements\n # that aren't in view.\n retval = mark_safe(retval.replace('

', '

' + ('
' * 100)))\n return retval\n\n class Meta:\n model = Thing\n fields = '__all__'\n\n\ndef edit_thing(request, thing_id):\n thing = Thing.objects.get(id=int(thing_id))\n add_spacers = 'add_spacers' in request.GET\n add_js_delay = int(request.GET.get('add_js_delay', '0'))\n\n if request.method == \"POST\":\n if 'clear' in request.POST:\n thing = Thing(id=thing.id)\n thing.save()\n return HttpResponseRedirect(reverse('thing_cleared', kwargs={'thing_id': thing_id}))\n else:\n thing_form = ThingForm(data=request.POST,\n instance=thing,\n add_spacers=add_spacers)\n if thing_form.is_valid():\n thing_form.save()\n return HttpResponseRedirect(reverse('edit_thing', kwargs={'thing_id': thing_id}))\n else:\n thing_form = ThingForm(instance=thing,\n add_spacers=add_spacers)\n\n return render(request, \"django_functest/tests/edit_thing.html\",\n {'thing_form': thing_form,\n 'thing': thing,\n 'add_js_delay': add_js_delay,\n })\n\n\ndef list_things(request):\n return render(request, \"django_functest/tests/list_things.html\",\n {'things': Thing.objects.all()})\n\n\ndef thing_cleared(request, thing_id):\n thing = Thing.objects.get(id=int(thing_id))\n return render(request, \"django_functest/tests/thing_cleared.html\",\n {'thing': thing})\n","sub_path":"django_functest/tests/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"121967451","text":"import sys\nimport os\n\n\nclass ConfigDict(dict):\n\n def __init__(self, file_name):\n\n self._file_name = file_name\n if os.path.isfile(file_name):\n with open(file_name, 'r') as f:\n for line in f:\n line = line.rstrip()\n exploded = line.split('=', 1)\n dict.__setitem__(self, exploded[0], exploded[1])\n\n def __setitem__(self, key, value):\n dict.__setitem__(self, key, value)\n with open(self._file_name, 'w') as f:\n for k, v in self.iteritems():\n f.write(\"{0}={1}\\n\".format(k, v))\n\n\ncd = ConfigDict(\"config_file.txt\")\n\nif len(sys.argv) == 3:\n key = sys.argv[1]\n value = sys.argv[2]\n print ('writing data: {0}, {1}'.format(key, value))\n\n cd[key] = value\n\nelse:\n print ('reading data')\n for key in cd.keys():\n print (' {0}={1}'.format(key, cd[key]))\n","sub_path":"oop/assignment3.py","file_name":"assignment3.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"351178179","text":"'''\nreference labelme_json_to_dataset\nhere aim to voc_to_mask.png for U-Net\n'''\n\nimport numpy as np\nimport base64\nimport os\nimport os.path as osp\n\nimport PIL.Image\nimport scipy.io as sio\nimport skimage.io as io\n\nfrom labelme import utils\n\n\ndef voc_to_mask(img_path, contours, png_dir, mask_dir):\n\n filename = osp.basename(img_path).replace('jpg', 'png') # get the last filename of the path\n # print(filename)\n\n with open(img_path, 'rb') as f:\n imageData = f.read()\n imageData = base64.b64encode(imageData).decode('utf-8')\n img = utils.img_b64_to_arr(imageData)\n # print('img shape:', img.shape)\n # print(np.max(img))\n\n label_name_to_value = {'_background_': 0, 'bone': 1}\n\n lbl = utils.shapes_to_label(img.shape, contours, label_name_to_value)\n # print('mask shape:', lbl.shape)\n # print(np.max(lbl))\n\n PIL.Image.fromarray(img).save(osp.join(png_dir, filename))\n utils.lblsave(osp.join(mask_dir, filename), lbl)\n\n\n\nif __name__ == '__main__':\n\n src_img_path = r'E:\\Unet\\test'\n src_mat_path = r'E:\\ClearMats'\n png_dir = r'E:\\Unet\\pngImages'\n mask_dir = r'E:\\Unet\\labelImages'\n\n # a = io.imread(osp.join(src_img_path, 'L-4-4-001.jpg'), as_gray=True)\n # print('gray shape is:', a.shape)\n # print('gray max is:', np.max(a))\n # print('gray min is:', np.min(a))\n\n if not osp.exists(png_dir):\n os.mkdir(png_dir)\n\n if not osp.exists(mask_dir):\n os.mkdir(mask_dir)\n\n for file in os.listdir(src_img_path):\n img_path = osp.join(src_img_path, file)\n # with open(img_path, 'rb') as f:\n # imageData = f.read()\n # imageData = base64.b64encode(imageData).decode('utf-8')\n # img = utils.img_b64_to_arr(imageData)\n #\n # PIL.Image.fromarray(img).save(osp.join(r'E:\\Unet\\test\\png', file.replace('jpg', 'png')))\n\n mat_path = osp.join(src_mat_path, file+'.mat')\n mat = sio.loadmat(mat_path)\n contours = []\n x = mat['x']\n y = mat['y']\n n = len(x) // 4 * 4\n for i in range(0, n, 4):\n xx = x[i:i+4]\n yy = y[i:i+4]\n bbox = zip(xx, yy) # [(x1,y1), (x2,y2), (x3,y3), (x4,y4)]\n contours.append(bbox)\n\n voc_to_mask(img_path, contours, png_dir, mask_dir)\n","sub_path":"labelme/json_to_dataset.py","file_name":"json_to_dataset.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"600252330","text":"# Node class \nclass Node: \n \n # Function to initialise the node object \n def __init__(self, data,next=None):\n self.data=data\n self.next=next\n \nclass LinkedList: \n \n def __init__(self): \n self.head = None\n self.len = 0\n \n def push(self, new_data): \n self.head =Node(new_data,self.head)\n self.len += 1\n \n # Function to get the middle of \n # the linked list \n def printMiddle(self):\n ptr=self.head\n for i in range(self.len//2):\n ptr=ptr.next\n print(ptr.data)\n\n# Driver code \nlist1 = LinkedList() \nlist1.push(5) \nlist1.push(4) \nlist1.push(2) \nlist1.push(3) \nlist1.push(1) \nlist1.printMiddle() \n","sub_path":"Exercise_3.py","file_name":"Exercise_3.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"275958722","text":"# 2015-06-14 Runtime: 836 ms\nclass Solution:\n # @param {character[][]} board\n # @return {void} Do not return anything, modify board in-place instead.\n def solveSudoku(self, board):\n self.board = board\n self.solve()\n \n # @return {boolean} True if a valid solution is found \n def solve(self):\n for i in xrange(9):\n for j in xrange(9):\n if self.board[i][j] == '.':\n for char in self.getFitCharList(i, j):\n self.board[i][j] = char\n if self.solve(): return True\n self.board[i][j] = '.'\n return False\n return True\n \n # @param {int} i\n # @param {int} j\n # @return {List} a list of available characters for board[i][j]\n def getFitCharList(self, m, n):\n L = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n for char in self.board[m]:\n if char != '.': L.remove(char)\n for i in xrange(9):\n if self.board[i][n] != '.' and self.board[i][n] in L: L.remove(self.board[i][n])\n for i in (m / 3 * 3, m / 3 * 3 + 1, m / 3 * 3 + 2):\n for j in (n / 3 * 3, n / 3 * 3 + 1, n / 3 * 3 + 2):\n if self.board[i][j] != '.'and self.board[i][j] in L: L.remove(self.board[i][j])\n return L","sub_path":"37_Sudoku_Solver.py","file_name":"37_Sudoku_Solver.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"624141514","text":"# Used for proxy SSH and other services via a jump server, reducing lantency\nlocal_port = input(\"Enter local port: \")\nremote_port = input(\"Enter remote port(22): \")\nif remote_port == '':\n remote_port = \"22\"\nlocal_addr = input(\"Enter localaddr(auto): \")\nif local_addr == '':\n import socket\n local_addr = socket.gethostbyname(socket.gethostname())\nremote_addr = input(\"Enter remote addr: \")\n\nprint(\"iptables -t nat -A PREROUTING -p tcp -m tcp --dport %s -j DNAT --to-destination %s:%s\" % (local_port, remote_addr, remote_port))\nprint(\"iptables -t nat -A POSTROUTING -d %s -p tcp -m tcp --dport %s -j SNAT --to-source %s\" % (remote_addr, remote_port, local_addr))\n","sub_path":"iptables/proxy_by_port.py","file_name":"proxy_by_port.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"517331108","text":"import requests\nfrom ._URLTimeoutCommon import *\n\nclass URLTimeoutRequests(URLGetter):\n def get(self, url, headers={}, ref=None, data=None, ignore_move=False, proxy=None):\n r = requests.get(url, headers=headers)\n\n if r.status_code == 304:\n raise URLOldDataError\n\n if r.status_code != 200:\n raise URLTimeoutError(str(r.status_code)+\" \"+r.reason,url, r.status_code)\n\n return URLObject(url, None, r.content, r.headers, data)\n","sub_path":"URLTimeoutRequests.py","file_name":"URLTimeoutRequests.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"387734087","text":"import unittest\ntry:\n import cryptography\n # slightly hacky way of preventing flake8 from complaining\n cryptography_imported = bool(cryptography)\nexcept ImportError:\n cryptography_imported = False\n\nfrom globus_cli.helpers import fill_delegate_proxy_activation_requirements\nfrom tests.framework.cli_testcase import CliTestCase\nfrom tests.framework.constants import GO_EP1_ID, PUBLIC_KEY\n\n\nclass DelegateProxyTests(CliTestCase):\n\n @unittest.skipIf(cryptography_imported, \"cryptography was imported\")\n def test_cryptography_not_imported(self):\n \"\"\"\n Confirms --delegate-proxy doesn't appear in activate help text\n if cryptography is not available. Confirms error if option is attempted\n to be used anyways.\n \"\"\"\n output = self.run_line(\"globus endpoint activate --help\")\n self.assertNotIn(\"--delegate-proxy\", output)\n\n output = self.run_line((\n \"globus endpoint activate {} --delegate-proxy cert.pem\"\n .format(GO_EP1_ID)), assert_exit_code=1)\n self.assertIn(\"Missing cryptography dependency\", output)\n\n @unittest.skipIf(not cryptography_imported, \"cryptography not imported\")\n def test_cryptography_imported(self):\n \"\"\"\n Confirms --delegate-proxy does appear in activate help text if\n cryptography was successfully imported.\n Confirms the tutorial endpoints cannot use delegate_proxy activation.\n \"\"\"\n output = self.run_line(\"globus endpoint activate --help\")\n self.assertIn(\"--delegate-proxy\", output)\n\n # --force and --no-autoactivate are used to prevent the endpoint being\n # seen as not needing activation\n output = self.run_line((\n \"globus endpoint activate {} --delegate-proxy cert.pem \"\n \"--no-autoactivate --force\".format(GO_EP1_ID)), assert_exit_code=1)\n self.assertIn(\n \"this endpoint does not support Delegate Proxy activation\", output)\n\n @unittest.skipIf(not cryptography_imported, \"cryptography not imported\")\n def test_fill_delegate_proxy_activation_requirements(self):\n \"\"\"\n Uses the public key from constants to form a fake activation\n requirements response, and an expired proxy to test\n fill_delegate_proxy_activation_requirements.\n \"\"\"\n # file containing an expired x509 from a myproxy-logon\n x509 = \"tests/framework/files/cert.pem\"\n\n activation_requirements = {\n \"DATA_TYPE\": \"activation_requirements\",\n \"DATA\": [\n {\"DATA_TYPE\": \"activation_requirement\",\n \"type\": \"delegate_proxy\",\n \"name\": \"public_key\",\n \"value\": PUBLIC_KEY},\n {\"DATA_TYPE\": \"activation_requirement\",\n \"type\": \"delegate_proxy\",\n \"name\": \"proxy_chain\",\n \"value\": None}]}\n\n filled_requirements = fill_delegate_proxy_activation_requirements(\n activation_requirements, x509)\n\n # assert the proxy_chain now contains a certificate\n self.assertIn(\"-----BEGIN CERTIFICATE-----\",\n filled_requirements[\"DATA\"][1][\"value\"])\n self.assertIn(\"-----END CERTIFICATE-----\",\n filled_requirements[\"DATA\"][1][\"value\"])\n\n @unittest.skipIf(not cryptography_imported, \"cryptography not imported\")\n def test_bad_x509(self):\n \"\"\"\n Uses the public key from constants to form a fake activation\n requirements response, then attempts to fill the activation\n requirements with bad x509 files. Confirms value errors\n \"\"\"\n activation_requirements = {\n \"DATA_TYPE\": \"activation_requirements\",\n \"DATA\": [\n {\"DATA_TYPE\": \"activation_requirement\",\n \"type\": \"delegate_proxy\",\n \"name\": \"public_key\",\n \"value\": PUBLIC_KEY},\n {\"DATA_TYPE\": \"activation_requirement\",\n \"type\": \"delegate_proxy\",\n \"name\": \"proxy_chain\",\n \"value\": None}]}\n\n # no file\n with self.assertRaises(IOError) as err:\n fill_delegate_proxy_activation_requirements(\n activation_requirements, \"nosuchfile.pem\")\n self.assertIn(\"No such file\", str(err.exception))\n\n # non pem file\n with self.assertRaises(ValueError) as err:\n fill_delegate_proxy_activation_requirements(\n activation_requirements, \"tests/framework/constants.py\")\n self.assertIn(\"Unable to parse PEM data\", str(err.exception))\n\n # no private key\n with self.assertRaises(ValueError) as err:\n fill_delegate_proxy_activation_requirements(\n activation_requirements, \"tests/framework/files/no_key.pem\")\n self.assertIn(\"Failed to decode PEM data\", str(err.exception))\n\n # only private key\n with self.assertRaises(ValueError) as err:\n fill_delegate_proxy_activation_requirements(\n activation_requirements, \"tests/framework/files/no_cert.pem\")\n self.assertIn(\"Unable to parse PEM data\", str(err.exception))\n","sub_path":"tests/unit/test_delegate_proxy.py","file_name":"test_delegate_proxy.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"207863771","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r\"create/$\", views.CreateProject.as_view(), name=\"create\"),\n url(r\"list/$\", views.ProjectListSearch.as_view(), name=\"search\"),\n url(r\"list/(?P.+)/$\", views.ProjectListSearch.as_view(), name=\"search\"),\n url(r\"detail/(?P\\d+)/$\", views.ProjectDetail.as_view(), name=\"detail\"),\n url(r\"edit/(?P\\d+)/$\", views.ProjectEdit.as_view(), name=\"edit\"),\n url(r\"delete/(?P\\d+)/$\", views.ProjectDelete.as_view(), name=\"delete\"),\n url(r\"apply/(?P\\d+)/$\", views.ApplyForPosition.as_view(), name=\"apply\"),\n url(r\"applications/$\", views.ApplicationsView.as_view(), name=\"applications\"),\n url(r\"applications/(?P.*)/(?P.*)/(?P.*)/$\",\n views.ApplicationsView.as_view(), name=\"applications\"),\n url(r'decide/(?P\\d+)/(?P\\d+)/$', views.ChangeApplicantStatus.as_view(), name='decide'),\n\n]\n","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"399026555","text":"class CairoPackage (CairoGraphicsXzPackage):\n\tdef __init__ (self):\n\t\tCairoGraphicsXzPackage.__init__ (self, 'cairo', '1.14.2')\n\n\t\t#This package would like to be built with fat binaries\n\t\t# if Package.profile.m64 == True:\n\t\t# \tself.fat_build = True\n\n\tdef build (self):\n\n\t\tif Package.profile.name == 'darwin':\n\t\t\tself.configure_flags.extend ([\n\t\t\t\t'--disable-gl',\n\t\t\t\t'--enable-quartz',\n\t\t\t\t'--enable-quartz-font',\n\t\t\t\t'--enable-quartz-image',\n\t\t\t\t'--disable-silent-rules',\n\t\t\t\t'--disable-symbol-lookup',\n\t\t\t\t'--disable-xlib',\n\t\t\t\t'--disable-xlib-xcb',\n\t\t\t\t'--disable-xcb',\n\t\t\t\t'--disable-xcb-shm',\n\t\t\t\t'--without-x',\n\t\t\t\t'--enable-ft',\n\t\t\t\t'--enable-pdf',\n\t\t\t\t'--enable-png',\n\t\t\t\t'--enable-ps',\n\t\t\t\t'--enable-script',\n\t\t\t\t'--enable-svg',\n\t\t\t\t'--enable-tee',\n\t\t\t\t'--enable-xml'\t\t\t\t\n\t\t\t])\n\t\telif Package.profile.name == 'linux':\n\t\t\tself.configure_flags.extend ([\n\t\t\t\t'--disable-quartz',\n\t\t\t\t'--with-x'\n\t\t\t])\n\n\t\tPackage.build (self)\n\nCairoPackage ()\n","sub_path":"packages/cairo.py","file_name":"cairo.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"164598843","text":"from django.conf.urls import url,include\nfrom django.contrib import admin\nfrom sora_main import views\n\napp_name = 'main'\nurlpatterns = [\n \n url(r'^search/$', views.search, name='search'),\n url(r'^information/$', views.infromation, name='information'),\n url(r'^login/$', views.login, name='login'),\n url(r'^index/$', views.index, name='index'),\n]","sub_path":"sora_main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"130984888","text":"import random\nfrom tkinter import *\nclass Guess:\n \n \n \n def __init__(self):\n \n win = Tk()\n win.title(\"Guess\")\n win.geometry(\"300x300\")\n \n self.List1 = [i for i in range(1,101)]\n self.x = random.choice(self.List1)\n# print(self.x)\n self.count=3\n \n Label(win,text = \"GUESS GAME\").place(x=110,y=20)\n var = StringVar()\n label1 = Message(win,textvariable = var,width=180).place(x=60,y=50)\n var.set(\"Guess a number between (1-100) if it matches with the system's guess you WIN.\")\n \n Label(win,text = \"Enter your number below\").place(x=80,y=120)\n self.v1 = IntVar()\n self.v1.set(\" \")\n entry1 = Entry(win,textvariable=self.v1,width=10).place(x=118,y=150)\n l1 = Label(win,text = \"Hint:\").place(x=80,y=175)\n self.l2 = Label(win,text = \" \")\n self.l2.place(x=120,y=175)\n \n b1 = Button(win,text=\"Check\",command=self.guess)\n b1.place(x=130,y=200)\n \n b2 = Button(win,text=\"Resest\",command=self.reset)\n b2.place(x=200,y=200)\n win.mainloop()\n \n def guess(self):\n \n \n if(self.v1.get()==self.x):\n self.l2[\"text\"]=\"Right Guess You won\"\n\n\n elif(self.v1.get()\", \"S\"), (\"\", \"S\")] +\n sentence +\n [(\"\", \"S\"), (\"\", \"S\")])\n sentence = [] \n continue\n if type == 'ner':\n for words in line.strip().split():\n if test:\n text = words.strip().split() \n sentence.append((text[0],\"\")) \n else:\n text, label = words.strip().split(\"/\",1)\n sentence.append((text, label))\n if type == 'pos':\n if test:\n text = line.strip().split() \n sentence.append((text[0],\"\")) \n else:\n text, label = line.strip().split(\" \",1)\n sentence.append((text, label)) \n return sentencesList\n\n\ntrainData = [item for sublist in read_data(sys.argv[1], sys.argv[4], False) for item in sublist]\ndevData = [item for sublist in read_data(sys.argv[2],sys.argv[4],False) for item in sublist]\ntestData = [item for sublist in read_data(sys.argv[3], sys.argv[4], True) for item in sublist] \n\n\nfor i in range(len(trainData)):\n if trainData[i][1] != 'S':\n windowTrain.append(([trainData[i-2][0],trainData[i-1][0],trainData[i][0],trainData[i+1][0],trainData[i+2][0]],trainData[i][1]))\n\nfor i in range(len(devData)): \n if devData[i][1] != 'S':\n windowDev.append(([devData[i-2][0],devData[i-1][0],devData[i][0],devData[i+1][0],devData[i+2][0]],devData[i][1]))\n\n\nfor i in range(len(testData)):\n if testData[i][1] != 'S':\n windowTest.append(([testData[i-2][0],testData[i-1][0],testData[i][0],testData[i+1][0],testData[i+2][0]]))\n\n\ntag = [a[1] for a in trainData]\nwords = [a[0] for a in trainData]\n\nvocab = set(words)\nvocab.add(\"UUUNKKK\")\ntags = set(tag)\ntags.add(\"UUUNKKK\")\n\n\nconfig.VOCAB = len(vocab)\nconfig.OUTPUT_SIZE = len(tags)\n\nwordToId = { word: i for i, word in enumerate(vocab)} \nidToWord = { i: word for i, word in enumerate(vocab)}\ntagToId = { tag: i for i, tag in enumerate(tags)}\nidToTaG = { i: tag for i, tag in enumerate(tags)}\n\ndef getWordOfId(Id):\n return idToWord[Id]\n\ndef getIdOfWord(word):\n ans = None \n if word in wordToId:\n ans = wordToId[word]\n else:\n ans = wordToId[\"UUUNKKK\"] \n return ans \n \ndef getTagOfId(Id):\n return idToTaG[Id]\n\ndef getIdOfTag(tag): \n ans = None \n if tag in tagToId:\n ans = tagToId[tag]\n else:\n ans = tagToId[\"UUUNKKK\"]\n return ans \n\n\n\n\n","sub_path":"utils1.py","file_name":"utils1.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"398643026","text":"import json\nimport re\nimport pprint\n\nbuiltJson = {}\nhtml = open(\"test.txt\", 'r').read().replace(\"\\n\", \"\")\n\nairports = html.split('')\n\nfor a in airports:\n tags = re.findall(\"\", a) + re.findall(\"<\\w+>\", a)\n for t in tags:\n a = a.replace(t, ' ')\n raw = a.split()\n for i,x in enumerate(raw):\n if len(x) == 2:\n break\n state = ' '.join(raw[:i]).lower()\n builtJson[state] = {}\n formatted = raw[i+1:]\n fullName = \"\"\n for f in formatted:\n f = f.replace(\" \", '').replace(\"\\n\", \"\")\n if len(f) != 3 or f[1].islower():\n fullName += f + \" \"\n else:\n fullName, abrev = ' '.join(fullName.replace(\"\\n\", \"\").split()), f.replace(\" \", '').replace(\"\\n\", '')\n builtJson[state][fullName] = abrev\n fullName = \"\"\n\njson.dump(builtJson, open(\"airportsJson.json\", 'w'))\n\n","sub_path":"utils/fix.py","file_name":"fix.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"495163754","text":"import os\nimport requests\nimport jinja2\nfrom kazoo.client import KazooClient\nfrom kazoo.recipe.watchers import DataWatch, ChildrenWatch\nfrom kazoo.protocol.states import EventType\nfrom twisted.internet import inotify, task\nfrom twisted.python import filepath\n\nfrom superwiser.common.log import logger\nfrom superwiser.common.path import PathMaker\nfrom superwiser.common.parser import manipulate_numprocs, build_conf\nfrom superwiser.common.parser import parse_content, unparse, extract_section\nfrom superwiser.common.parser import section_from_program\nfrom superwiser.common.parser import extract_prog_tuples, extract_programs\nfrom superwiser.master.distribute import distribute_work\nfrom superwiser.master.rpcutils import TimeoutServerProxy\n\n\nclass EyeOfMordor(object):\n def __init__(self, host, port, auto_redistribute, **kwargs):\n self.zk = KazooClient('{}:{}'.format(host, port))\n self.path = PathMaker()\n self.auto_redistribute = auto_redistribute\n self.node_drop_callbacks = kwargs.get('node_drop_callbacks', [])\n self.supervisor_down_callbacks = kwargs.get(\n 'supervisor_down_callbacks', [])\n self.supervisor_poll_interval = kwargs.get(\n 'supervisor_poll_interval', 15)\n self.project_dir = kwargs['project_dir']\n self.toolchains = []\n self.setup()\n\n def setup(self):\n logger.info('Setting up the Eye of Mordor')\n self.zk.start()\n # Setup paths\n self.setup_paths()\n # Initializse children\n self.toolchains = self.zk.get_children(self.path.toolchain())\n # Remove dangling nodes if any\n self.remove_dangling_nodes()\n # Register watches\n self.register_watches()\n # Setup looping call to poll for supervisor states\n self.setup_poller()\n\n def remove_dangling_nodes(self):\n \"\"\" Remove nodes to sync the children in the toolchains and the nodes\n on zookeeper in case there have been some node drops while master was\n away.\n \"\"\"\n all_nodes = self.zk.get_children(self.path.node())\n dangling_nodes = set(all_nodes) - set(self.toolchains)\n if dangling_nodes:\n logger.info(\"Found some dangling nodes. Will remove them from the cluster\")\n for node in dangling_nodes:\n logger.info(\"Removing dangling node : \" + self.get_orc_ip(node))\n self.zk.delete(self.path.node(node))\n\n def is_supervisor_running(self, host):\n server = TimeoutServerProxy(\n 'http://sauron:lotr@{}:9001/RPC2'.format(host),\n timeout=3)\n try:\n state = server.supervisor.getState()\n return state['statecode'] == 1\n except Exception as e:\n err_msg = 'Supervisor state check failed. host: {host} msg: {msg}'\n logger.warn(err_msg.format(host=host, msg=e.message))\n return False\n\n def setup_poller(self):\n logger.info('Setting up poller')\n\n def poller():\n logger.info('Polling nodes for supervisor state check')\n hosts = [self.get_orc_ip(orc) for orc in self.list_orcs()]\n # Iterate over every orc and poll for supervisor state\n for host in hosts:\n if not self.is_supervisor_running(host):\n logger.warn('Supervisor on {} is not running'.format(host))\n # Hit the registered callback to indicate that\n # supervisor is not running\n for cb in self.supervisor_down_callbacks:\n logger.info('Hitting callback. Host: ' + cb['url'])\n try:\n requests.post(\n cb['url'],\n json={\n 'host': host,\n 'event': 'supervisor_down',\n 'token': cb.get('auth_token', '')\n },\n timeout=3)\n except Exception as e:\n err_msg = 'Callback failed. host: {host}, ' \\\n 'msg: {msg}'\n logger.warn(err_msg.format(host=cb['url'],\n msg=e.message))\n\n logger.info('Supervisor state check poll complete')\n\n loop = task.LoopingCall(poller)\n loop.start(self.supervisor_poll_interval)\n\n def setup_paths(self):\n logger.info('Setting up paths')\n self.zk.ensure_path(self.path.toolchain())\n self.zk.ensure_path(self.path.node())\n self.zk.ensure_path(self.path.baseconf())\n self.zk.ensure_path(self.path.stateconf())\n self.zk.ensure_path(self.path.stateconfbkp())\n\n def register_watches(self):\n logger.info('Registering watches')\n DataWatch(self.zk, self.path.baseconf(), self.on_base_conf_change)\n DataWatch(self.zk, self.path.stateconf(), self.on_state_conf_change)\n ChildrenWatch(\n self.zk, self.path.toolchain(),\n self.on_toolchains, send_event=True)\n\n def interpolate_vars_in_conf(self, conf):\n t = jinja2.Template(conf)\n return t.render(\n PYTHON='python',\n PROJECT_DIR=self.project_dir).encode('utf8')\n\n def _distribute(self, work, toolchains):\n # Distribute conf across toolchains\n assigned_work = distribute_work(work, toolchains)\n for (toolchain, awork) in assigned_work.items():\n conf = self.interpolate_vars_in_conf(\n unparse(build_conf(awork, parse_content(work))))\n self.zk.set(\n self.path.toolchain(toolchain),\n conf)\n\n def distribute(self):\n self._distribute(\n self.get_state_conf(),\n self.zk.get_children(self.path.toolchain()))\n\n def on_base_conf_change(self, data, stat, event):\n if event and event.type == EventType.CHANGED:\n logger.info('Handling base conf change')\n state_programs = {\n name: (numprocs, weight)\n for name, numprocs, weight in extract_prog_tuples(\n parse_content(self.get_state_conf()))}\n base_conf = parse_content(data)\n base_tuples = extract_prog_tuples(base_conf)\n # Rebuild state conf\n prog_tuples = []\n for (program_name, numprocs, weight) in base_tuples:\n tup = (program_name, )\n if program_name in state_programs:\n tup += state_programs[program_name]\n else:\n tup += (numprocs, weight)\n\n prog_tuples.append(tup)\n # Trigger distribute\n state_conf = unparse(build_conf(prog_tuples, base_conf))\n self.set_state_conf(state_conf)\n\n def on_state_conf_change(self, data, stat, event):\n if event and event.type == EventType.CHANGED:\n logger.info('Handling state conf change')\n # Get toolchains\n toolchains = self.zk.get_children(self.path.toolchain())\n if toolchains:\n # Distribute work across toolchains\n self._distribute(data, toolchains)\n\n def on_toolchains(self, children, event):\n if not event:\n return\n added = list(set(children) - set(self.toolchains))\n removed = list(set(self.toolchains) - set(children))\n if added:\n logger.info('Toolchain joined')\n self.distribute()\n elif removed:\n logger.info('Toolchain left')\n host_ip = self.get_orc_ip(removed[0])\n logger.info('IP : ' + host_ip)\n # Hit callbacks\n for cb in self.node_drop_callbacks:\n logger.info('Hitting callback. Host: ' + cb['url'])\n\n try:\n requests.post(cb['url'],\n json={\n 'node_count': len(children),\n 'node': host_ip,\n 'event': 'toolchain_dropped',\n 'token': cb.get('auth_token', ''),\n },\n timeout=3)\n except Exception as e:\n err_msg = 'Callback failed. host: {host}, msg: {msg}'\n logger.warn(err_msg.format(host=cb['url'], msg=e.message))\n self.zk.delete(self.path.node(removed[0]))\n if self.auto_redistribute:\n self.distribute()\n self.toolchains = children\n\n def get_base_conf(self):\n logger.info('Getting base conf')\n data, _ = self.zk.get(self.path.baseconf())\n return data\n\n def set_base_conf(self, conf):\n logger.info('Updating base conf')\n self.zk.set(self.path.baseconf(), conf)\n\n def get_state_conf(self):\n logger.info('Getting state conf')\n data, _ = self.zk.get(self.path.stateconf())\n return data\n\n def set_state_conf(self, conf):\n logger.info('Updating state conf')\n self.zk.set(self.path.stateconf(), conf)\n\n def get_bkp_conf(self):\n logger.info('Getting backed up conf')\n data, _ = self.zk.get(self.path.stateconfbkp())\n return data\n\n def teardown(self):\n logger.info('Tearing down the eye of Mordor!')\n self.zk.stop()\n self.zk.close()\n\n def list_orcs(self):\n return self.zk.get_children(self.path.toolchain())\n\n def get_orc_ip(self, orc):\n return self.zk.get(self.path.node(orc))[0]\n\n def list_processes_for_orc(self, orc):\n return extract_prog_tuples(\n parse_content(self.zk.get(self.path.toolchain(orc))[0]))\n\n def list_processes(self):\n # Build list of processes for each orc\n procs = []\n for orc in self.list_orcs():\n procs.extend(self.list_processes_for_orc(orc))\n\n # Remap tuples with program body\n parsed = parse_content(self.get_state_conf())\n out = {}\n for proc in procs:\n out[proc[0]] = extract_section(\n parsed,\n section_from_program(proc[0]))\n\n return out\n\n def backup_state(self):\n logger.info('Backing up state')\n self.zk.set(\n self.path.stateconfbkp(),\n self.get_state_conf())\n\n def restore_state(self):\n logger.info('Restoring state')\n self.set_state_conf(self.get_bkp_conf())\n\n def get_stopped_processes(self):\n base_tups = extract_prog_tuples(\n parse_content(self.get_base_conf()))\n state_tups = extract_prog_tuples(\n parse_content(self.get_state_conf()))\n base_progs = set(ele[0] for ele in base_tups)\n state_progs = set(ele[0] for ele in state_tups)\n stopped_progs = (base_progs - state_progs)\n base_conf = extract_programs(parse_content(self.get_base_conf()))\n out = []\n for (name, body) in base_conf.items():\n if name in stopped_progs:\n body['name'] = name\n out.append(body)\n return out\n\n\nclass Sauron(object):\n def __init__(self, eye, conf, override_state, conf_path):\n self.eye = eye\n self.conf = conf\n self.override_state = override_state\n self.conf_path = conf_path\n self.notifier = None\n self.setup()\n\n def setup(self):\n logger.info('Setting up Sauron')\n if self.override_state:\n # Override previous state of conf\n self.eye.set_state_conf(self.conf)\n else:\n # Merge provided conf with state conf\n self.eye.set_base_conf(self.conf)\n # Register File Watcher\n notifier = inotify.INotify()\n notifier.startReading()\n notifier.watch(filepath.FilePath(\n self.conf_path), callbacks=[self.on_conf_change])\n self.notifer = notifier\n\n def on_conf_change(self, ignore, fp, mask):\n \"\"\"Callback to be invoked when the file at config path changes.\"\"\"\n if mask == inotify.IN_DELETE_SELF:\n logger.info('Handling conf path change')\n self.notifer.stopReading()\n notifier = inotify.INotify()\n notifier.startReading()\n notifier.watch(filepath.FilePath(fp.path),\n callbacks=[self.on_conf_change])\n self.notifer = notifier\n with fp.open() as conf:\n self.eye.set_base_conf(conf.read())\n elif mask == inotify.IN_MODIFY:\n with fp.open() as conf:\n self.eye.set_base_conf(conf.read())\n\n def increase_procs(self, program_name, factor=1):\n logger.info('Increasing procs')\n\n def adder(x):\n return x + factor\n\n new_conf = manipulate_numprocs(\n parse_content(self.eye.get_state_conf()),\n program_name,\n adder)\n # Simply set the conf to trigger a distribute and sync\n self.eye.set_state_conf(new_conf)\n\n return True\n\n def decrease_procs(self, program_name, factor=1):\n logger.info('Decreasing procs')\n\n def subtractor(x):\n return x - factor\n\n new_conf = manipulate_numprocs(\n parse_content(self.eye.get_state_conf()),\n program_name,\n subtractor)\n # Simply set the conf to trigger a distribute and sync\n self.eye.set_state_conf(new_conf)\n\n return True\n\n def get_previous_program_state(self, program_name):\n # Try getting program from backup state\n bkp_conf_tuples = extract_prog_tuples(\n parse_content(self.eye.get_bkp_conf()))\n try:\n program_tuple = next(ele for ele in bkp_conf_tuples\n if ele[0] == program_name)\n except StopIteration:\n # Try getting program from base conf\n base_conf_tuples = extract_prog_tuples(\n parse_content(self.eye.get_base_conf()))\n try:\n program_tuple = next(ele for ele in base_conf_tuples\n if ele[0] == program_name)\n except StopIteration:\n return None\n\n return program_tuple\n\n def start_program(self, program_name):\n prog_tuples = extract_prog_tuples(\n parse_content(self.eye.get_state_conf()))\n has_program = any(ele for ele in prog_tuples\n if ele[0] == program_name)\n if has_program:\n logger.info('Already contains program')\n return False\n\n program_tuple = self.get_previous_program_state(program_name)\n if program_tuple is None:\n logger.info('Program does not exist')\n return False\n # Program did not exist, let's add it now\n # Note: We set numprocs to one while adding\n prog_tuples.append(program_tuple)\n # Update conf and distribute\n self.eye.set_state_conf(\n unparse(\n build_conf(\n prog_tuples,\n parse_content(self.eye.get_base_conf()))))\n return True\n\n def stop_program(self, program_name):\n logger.info('Stopping program')\n conf = parse_content(self.eye.get_state_conf())\n # Check if program exists\n prog_tuples = extract_prog_tuples(conf)\n for (pos, (prog_name, _, _)) in enumerate(prog_tuples):\n if prog_name == program_name:\n del prog_tuples[pos]\n break\n else:\n logger.info('Program is either already stopped/not defined')\n return False\n # Backup state first to hold nummprocs of program\n self.eye.backup_state()\n self.eye.set_state_conf(\n unparse(\n build_conf(\n prog_tuples,\n conf)))\n return True\n\n def restart_program(self, program_name):\n self.stop_program(program_name)\n return self.start_program(program_name)\n\n def restart_all_programs(self):\n logger.info('Restarting all programs')\n self.stop_all_programs()\n return self.start_all_programs()\n\n def was_stopped(self):\n return self.eye.get_state_conf() == ''\n\n def stop_all_programs(self):\n \"\"\"We copy state conf onto a backup path first, truncate state conf\n and distribute.\n \"\"\"\n logger.info('Stopping all programs')\n self.eye.backup_state()\n # Now truncate state conf, which triggers a distribute.\n self.eye.set_state_conf('')\n return True\n\n def start_all_programs(self):\n logger.info('Starting all programs')\n # If state already contains conf, then do not override it\n state_conf = self.eye.get_state_conf()\n if state_conf != '':\n logger.info('State conf may be overidden. Skipping')\n return False\n # Restore the backup state, which triggers a distribute\n self.eye.restore_state()\n return True\n\n def teardown(self):\n logger.info('Tearing down Sauron')\n self.eye.teardown()\n\n\nclass SauronFactory(object):\n _instance = None\n\n def make_sauron(self, **kwargs):\n inst = SauronFactory._instance\n if inst is None:\n logger.info('Making Sauron')\n\n zk_host = kwargs['zookeeper_host']\n zk_port = kwargs['zookeeper_port']\n auto_redistribute = kwargs['auto_redistribute_on_failure']\n node_drop_callbacks = kwargs.get('node_drop_callbacks', [])\n supervisor_down_callbacks = kwargs.get(\n 'supervisor_down_callbacks', [])\n conf_path = kwargs['supervisor_conf']\n override_state = kwargs['override_state']\n supervisor_poll_interval = kwargs['supervisor_poll_interval']\n\n if not os.path.exists(conf_path):\n raise Exception('Supervisor conf does not exist')\n\n supervisor_conf = self.read_conf(conf_path)\n\n inst = Sauron(\n EyeOfMordor(\n host=zk_host,\n port=zk_port,\n auto_redistribute=auto_redistribute,\n node_drop_callbacks=node_drop_callbacks,\n supervisor_down_callbacks=supervisor_down_callbacks,\n supervisor_poll_interval=supervisor_poll_interval,\n project_dir=kwargs.get('project_dir', '')),\n supervisor_conf,\n override_state,\n conf_path)\n\n SauronFactory._instance = inst\n\n return inst\n\n def read_conf(self, path):\n logger.info('Reading conf')\n with open(path) as source:\n return source.read()\n","sub_path":"superwiser/master/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":18891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"367894270","text":"from subprocess import PIPE, STDOUT, run\nfrom config import EXEC_USERS, OWNER_ID\nfrom utils import long_reply\n\n\ndef execute(bot, update, args):\n user_id = update.effective_user.id\n\n if update.message.chat.type != \"private\":\n if user_id in EXEC_USERS: \n p = run(' '.join(args), shell=True, stdout=PIPE, stderr=STDOUT, close_fds=True, timeout=2)\n result = p.stdout.decode(\"utf-8\")\n if len(result) > 4096:\n long_reply(update, result)\n else:\n update.message.reply_text(result)\n\n else:\n update.message.reply_text(\"You're not allowed to execute.\")\n else:\n update.message.reply_text(\"You can't exec from private chat.\")\n\n\n","sub_path":"modules/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"587959504","text":"#! /usr/bin/env python3\n\nimport argparse\nimport os\nimport shutil\nimport numpy as np\nfrom typing import List\nfrom filter_domains import filter_domains\nimport rand_seed\n\n__author__ = 'Kevin C. Gall'\n\ndef read_map_file(input_file):\n map_info = {\n 'width': int(input_file.readline()),\n 'height': int(input_file.readline()),\n 'obstacles': set()\n }\n\n y = 0\n line = input_file.readline()\n while line != '':\n if line == '\\n':\n continue\n\n for x in range(map_info['width']):\n if line[x] == '#':\n map_info['obstacles'].add((x, y))\n\n y = y+1\n line = input_file.readline()\n\n return map_info\n\n\ndef create_gridworld_scene(base_map_info, num_goals, intervention_prob):\n \"\"\"Creates a scene with random start locations for observer and subject\"\"\"\n full_scene = base_map_info.copy()\n occupied = full_scene['obstacles'].copy()\n\n def get_point():\n return (\n np.random.randint(full_scene['width']),\n np.random.randint(full_scene['height'])\n )\n\n # randomly set observer and subject start locations\n\n # agent\n pt = get_point()\n while pt in occupied:\n pt = get_point()\n occupied.add(pt)\n full_scene['agent'] = pt\n\n # observer\n while pt in occupied:\n pt = get_point()\n occupied.add(pt)\n full_scene['observer'] = pt\n\n # randomly set goals\n full_scene['goals'] = set()\n for _ in range(num_goals):\n while pt in occupied:\n pt = get_point()\n occupied.add(pt)\n full_scene['goals'].add(pt)\n\n # randomly set remaining cells to be intervention cells or not\n full_scene['interventions'] = []\n for x in range(full_scene['width']):\n for y in range(full_scene['height']):\n pt = (x, y)\n if pt not in occupied and np.random.rand() < intervention_prob:\n full_scene['interventions'].append(pt)\n\n return full_scene\n\n\n\ndef write_gridworld_instance(full_map_info, out_file_path, tmp_alt_path):\n real_instance = open(out_file_path, 'w')\n temp_instance = open(tmp_alt_path, 'w')\n\n preamble = str(full_map_info['width'])+'\\n'+str(full_map_info['height'])+'\\n'\n world = preamble\n alt_world = preamble\n\n for y in range(0, full_map_info['height']):\n for x in range(0, full_map_info['width']):\n pt = (x, y)\n\n if pt == full_map_info['agent']:\n world += '@'\n alt_world += '_'\n elif pt == full_map_info['observer']:\n world += 'o'\n alt_world += '@'\n elif pt in full_map_info['goals']:\n world += '*'\n alt_world += '*'\n elif pt in full_map_info['obstacles']:\n world += '#'\n alt_world += '#'\n elif pt in full_map_info['interventions']:\n world += 'A'\n alt_world += 'A'\n else:\n world += '_'\n alt_world += '_'\n world += '\\n'\n alt_world += '\\n'\n\n real_instance.write(world)\n temp_instance.write(alt_world)\n\n real_instance.close()\n temp_instance.close()\n\n\ndef main(args):\n map_files: List[str] = args.maps\n resource_dir = args.resource_dir\n num_goals = args.goals\n num_scenes = args.num_scenes\n intervention_prob = args.intervention_probability\n out_path = args.path\n\n seed_skip = args.seed_skip\n rand_seed.skip_n_seeds(seed_skip)\n np.random.seed(rand_seed.next_seed())\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n alt_dir = os.path.join('./temp', out_path)\n if not os.path.exists(alt_dir):\n os.makedirs(alt_dir)\n\n for map_file in map_files:\n alt_instance_paths = []\n ext_index = map_file.rindex('.map')\n base_filename = map_file[:ext_index] + '-scn'\n with open(os.path.join(resource_dir, map_file)) as map_file:\n map_info = read_map_file(map_file)\n\n for i in range(num_scenes):\n out_file_path = os.path.join(out_path, base_filename + str(i) + '.vw')\n tmp_alt_path = os.path.join(alt_dir, base_filename + str(i) + '.vw')\n\n domain_instance = create_gridworld_scene(map_info, num_goals, intervention_prob)\n write_gridworld_instance(domain_instance, out_file_path, tmp_alt_path)\n alt_instance_paths.append(tmp_alt_path)\n\n if args.filter:\n domain_type = 'VACUUM_WORLD' if num_goals > 1 else 'GRID_WORLD'\n print('Checking for observer access to goals')\n passed = filter_domains(alt_instance_paths, base_filename, domain_type,\n '.vw', out_path, write=False)\n domain_instance_paths = ['/' + domain_path[5:] for domain_path in passed]\n print('Filtering from remaining')\n filter_domains(domain_instance_paths, base_filename, domain_type,\n '.vw', os.path.join(out_path, 'filtered'), write=True)\n\n shutil.rmtree(alt_dir)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Generate scenes for gridmaps.')\n\n parser.add_argument('maps', nargs='+',\n help='List of filenames to input domain maps')\n parser.add_argument('-r', '--resource-dir', type=str, required=True,\n help='Relative path to the directory that contains the map files')\n parser.add_argument('-n', '--num-scenes', type=int, required=True,\n help='Number of scenes to create for each passed map')\n parser.add_argument('-g', '--goals', help='total number of goals to generate', type=int, default=1)\n parser.add_argument('-i', '--intervention-probability', type=float, default=0.1,\n help='The probability that any given clear cell will have an intervention available')\n parser.add_argument('-p', '--path',\n help='directory path to save the scenes. MUST BE RELATIVE PATH to cwd', default='./gridmap')\n parser.add_argument('-f', '--filter', default=None, action='store_true',\n help='Filter generated domains to only solvable. Assumes a previous build of Metronome. Executes A_STAR on each domain.')\n parser.add_argument('--seed-skip', type=int, default=0,\n help='If passed, skip this many random seeds')\n\n main(args=parser.parse_args())","sub_path":"scripts/generator/generate_gridmap_scenes.py","file_name":"generate_gridmap_scenes.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"21988640","text":"# 일 평균 30만주이상 거래되는 nasdaq, newyork, amex 중 \r\n# 60일 거래량 평균 대비 60일내 일일 최대 거래량이 500% 이상인 종목(5_volume_follow.xlsx) 중\r\n# macd > 0 인 종목 추출\r\n# 일 1회 가동!!!(macd 0선 위 올라오는 신규종목 도출)(step4_volume_follow_w_macd.xlsx)\r\n\r\nfrom pandas_datareader import data as pdr\r\nimport yfinance as yf\r\nimport pandas as pd\r\nimport openpyxl\r\nimport datetime\r\nimport time\r\n\r\ndef macd(stick, period):\r\n df1 = pdr.get_data_yahoo(stick, start=period) \r\n\r\n # 12일 EMA = EMA12\r\n if len(df1.Close) < 26:\r\n print(\"Stock info is short\")\r\n\r\n # y = df.Close.values[0]\r\n # m_list = [y]\r\n y1 = df1.iloc[0]['Close']\r\n y2 = df1.iloc[0]['Close']\r\n m_list1 = [y1] \r\n m_list2 = [y2]\r\n # 12일 지수이동평균 계산\r\n for i in range(len(df1)):\r\n if i < 12:\r\n a12 = 2 / (i+1 + 1)\r\n else:\r\n a12 = 2 / (12 + 1)\r\n y1 = y1*(1-a12) + df1.Close.values[i]*a12\r\n m_list1.append(y1)\r\n\r\n # 26일 지수이동평균 계산 \r\n for k in range(len(df1)):\r\n if k < 26:\r\n a26 = 2 / (k+1 + 1)\r\n else:\r\n a26 = 2 / (26 + 1)\r\n y2 = y2*(1-a26) + df1.Close.values[k]*a26\r\n m_list2.append(y2)\r\n \r\n \r\n # macd 계산\r\n # print(m_list1)\r\n # print(m_list2)\r\n macd = m_list1[-1] - m_list2[-1]\r\n # print(macd)\r\n return macd\r\n\r\nyf.pdr_override()\r\nwb = openpyxl.Workbook()\r\nsheet = wb.active\r\n# cell name 생성\r\nsheet.append(['time', 'market', 'symbol', 'code', 'company_name', 'price', 'vol_max', 'vol_mean', 'industry', 'macd'])\r\nwb.save('step4_volume_follow_w_macd.xlsx')\r\n\r\n#회사 데이터 읽기\r\ndf_com = pd.read_excel(\"step3_volume_follow.xlsx\")\r\nnow = datetime.datetime.now()\r\nstart_day = '2021-01-01'\r\n\r\ni = 1\r\nfor i in range(len(df_com)):\r\n # df = pdr.get_data_yahoo(df_com1.iloc[i]['Symbol'], period = '1mo') # 기간 1month\r\n df = pdr.get_data_yahoo(df_com.iloc[i]['symbol'], period = '70d') # 기간 10일\r\n df['vol_mean'] = df['Volume'].rolling(window=60).mean()\r\n df['vol_max'] = df['Volume'].rolling(window=60).max()\r\n df['high_max_60'] = df['Close'].rolling(window=60).max()\r\n \r\n # print(df)\r\n \r\n macd(df_com.iloc[i]['symbol'], start_day)\r\n if macd(df_com.iloc[i]['symbol'], start_day) > 0 :\r\n print(macd(df_com.iloc[i]['symbol'], start_day))\r\n sheet.append([now, df_com.iloc[i]['market'], df_com.iloc[i]['symbol'], df_com.iloc[i]['code'], \\\r\n df_com.iloc[i]['company_name'], df.iloc[-1]['Close'], df.iloc[-1]['vol_max'], df.iloc[-1]['vol_mean'],\\\r\n df_com.iloc[i]['industry'], macd(df_com.iloc[i]['symbol'], start_day)])\r\n wb.save('step4_volume_follow_w_macd.xlsx')\r\n print('macd 0선 위', df_com.iloc[i]['symbol'])\r\n \r\n i += 1 \r\n","sub_path":"step4_volume_follow_w_macd.py","file_name":"step4_volume_follow_w_macd.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"144469325","text":"import requests,sys,bs4\n\nres=requests.get('https://gadgets.ndtv.com/news')\t#request to a tech news website\n\ntry:\t\t\t\t\t#try block to check if news site is valid or not\n res.raise_for_status()\nexcept Exception as exc:\t#exception block to avoid abnormal termination\n print('There was a problem: %s' % (exc))\n sys.exit()\n\n#print(res.text[:500])\n\nnews_soup=bs4.BeautifulSoup(res.text,\"html.parser\")\t#beautiful soup for web sacraping\n\nfor elements in news_soup.find_all('span','news_listing'):\t#it was seen that headlines have a common html feature div class='news_listing' and hence this parsing\n\tprint(elements.getText())\t\t#printing headlines\n\n","sub_path":"web_scraping.py","file_name":"web_scraping.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"506162597","text":"# Copyright (C) 2013 DNAnexus, Inc.\n#\n# This file is part of dx-toolkit (DNAnexus platform client libraries).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nDXApplet Handler\n++++++++++++++++\n\nApplets are data objects that store application logic, including\nspecifications for executing it, and (optionally) input and output\nsignatures. They can be run by calling the :func:`DXApplet.run` method.\n\n\"\"\"\n\nimport dxpy\nfrom dxpy.bindings import *\nfrom dxpy.utils import merge\n\nclass DXExecutable:\n '''Methods in :class:`!DXExecutable` are used by both\n :class:`~dxpy.bindings.dxapp.DXApp` and\n :class:`~dxpy.bindings.dxapplet.DXApplet`.\n '''\n def __init__(self, *args, **kwargs):\n raise NotImplementedError(\"This class is a mix-in. Use DXApp or DXApplet instead.\")\n\n def run(self, executable_input, project=None, folder=\"/\", name=None, tags=None, properties=None, details=None,\n instance_type=None, depends_on=None, delay_workspace_destruction=None,\n extra_args=None, **kwargs):\n '''\n :param executable_input: Hash of the executable's input arguments\n :type executable_input: dict\n :param project: Project ID of the project context\n :type project: string\n :param folder: Folder in which executable's outputs will be placed in *project*\n :type folder: string\n :param name: Name for the new job (default is \"\")\n :type name: string\n :param tags: Tags to associate with the job\n :type tags: list of strings\n :param properties: Properties to associate with the job\n :type properties: dict with string values\n :param details: Details to set for the job\n :type details: dict or list\n :param instance_type: Instance type on which the jobs will be run, or a dict mapping function names to instance type requests\n :type instance_type: string or dict\n :param depends_on: List of data objects or jobs to wait that need to enter the \"closed\" or \"done\" states, respectively, before the new job will be run; each element in the list can either be a dxpy handler or a string ID\n :type depends_on: list\n :param delay_workspace_destruction: Whether to keep the job's temporary workspace around for debugging purposes for 3 days after it succeeds or fails\n :type delay_workspace_destruction: boolean\n :param extra_args: If provided, a hash of options that will be merged into the underlying JSON given for the API call\n :type extra_args: dict\n :returns: Object handler of the newly created job\n :rtype: :class:`~dxpy.bindings.dxjob.DXJob`\n\n Creates a new job that executes the function \"main\" of this executable with\n the given input *executable_input*.\n\n '''\n if project is None:\n project = dxpy.WORKSPACE_ID\n\n run_input = {\"input\": executable_input,\n \"folder\": folder}\n if name is not None:\n run_input[\"name\"] = name\n if tags is not None:\n run_input[\"tags\"] = tags\n if properties is not None:\n run_input[\"properties\"] = properties\n if instance_type is not None:\n if isinstance(instance_type, basestring):\n run_input[\"systemRequirements\"] = {\"*\": {\"instanceType\": instance_type}}\n elif isinstance(instance_type, dict):\n run_input[\"systemRequirements\"] = {stage: {\"instanceType\": stage_inst} for stage, stage_inst in instance_type.iteritems()}\n else:\n raise DXError('Expected instance_type field to be either a string or a dict')\n\n if depends_on is not None:\n run_input[\"dependsOn\"] = []\n if isinstance(depends_on, list):\n for item in depends_on:\n if isinstance(item, DXJob) or isinstance(item, DXDataObject):\n if item.get_id() is None:\n raise DXError('A dxpy handler given in depends_on does not have an ID set')\n run_input[\"dependsOn\"].append(item.get_id())\n elif isinstance(item, basestring):\n run_input['dependsOn'].append(item)\n else:\n raise DXError('Expected elements of depends_on to only be either instances of DXJob or DXDataObject, or strings')\n else:\n raise DXError('Expected depends_on field to be a list')\n\n if details is not None:\n run_input[\"details\"] = details\n\n if delay_workspace_destruction is not None:\n run_input[\"delayWorkspaceDestruction\"] = delay_workspace_destruction\n\n if dxpy.JOB_ID is None:\n run_input[\"project\"] = project\n\n if extra_args is not None:\n merge(run_input, extra_args)\n\n if isinstance(self, DXApplet):\n return DXJob(dxpy.api.applet_run(self._dxid, run_input, **kwargs)[\"id\"])\n elif isinstance(self, dxpy.bindings.DXAnalysisWorkflow):\n return DXAnalysis(dxpy.api.workflow_run(self._dxid, run_input, **kwargs)[\"id\"])\n elif self._dxid is not None:\n return DXJob(dxpy.api.app_run(self._dxid, input_params=run_input, **kwargs)[\"id\"])\n else:\n return DXJob(dxpy.api.app_run('app-' + self._name, alias=self._alias,\n input_params=run_input,\n **kwargs)[\"id\"])\n\n\n############\n# DXApplet #\n############\n\ndef _makeNonexistentAPIWrapper(method):\n def nonexistentAPIWrapper(object_id, input_params=None, always_retry=None, **kwargs):\n raise DXError(\"Wrapper for \" + method + \" does not exist\")\n return nonexistentAPIWrapper\n\nclass DXApplet(DXDataObject, DXExecutable):\n '''\n Remote applet object handler.\n\n .. py:attribute:: runSpec\n\n The applet's run specification (a dict indicating, among other things, how the code of the\n applet is to be interpreted). See `the API docs for Run Specification\n `_\n for more information.\n\n .. py:attribute:: dxapi\n\n String containing the version of the DNAnexus API that the applet should run against.\n\n .. py:attribute:: access\n\n The applet's access requirements hash (a dict indicating any nonstandard permissions, such\n as requiring access to the internet, that are needed by the applet). See `the API docs for\n Access Requirements\n `_\n for more information.\n\n .. py:attribute:: title\n\n String containing the (human-readable) title of the app\n\n .. py:attribute:: summary\n\n String containing a short, one-line summary of the applet's purpose\n\n .. py:attribute:: description\n\n String of free-form text (`Markdown `_ syntax\n is supported) containing a description of the applet. The description is presented to users\n to help them understand the purpose of the app and how to invoke it.\n\n .. py:attribute:: developerNotes\n\n String of free-form text (`Markdown `_ syntax\n is supported) containing information about the internals or implementation details of the\n applet, suitable for developers or advanced users.\n\n .. automethod:: _new\n '''\n\n _class = \"applet\"\n\n _describe = staticmethod(dxpy.api.applet_describe)\n _add_types = staticmethod(_makeNonexistentAPIWrapper(\"/applet-xxxx/addTypes\"))\n _remove_types = staticmethod(_makeNonexistentAPIWrapper(\"/applet-xxxx/removeTypes\"))\n _get_details = staticmethod(dxpy.api.applet_get_details)\n _set_details = staticmethod(_makeNonexistentAPIWrapper(\"/applet-xxxx/setDetails\"))\n _set_visibility = staticmethod(_makeNonexistentAPIWrapper(\"/applet-xxxx/setVisibility\"))\n _rename = staticmethod(dxpy.api.applet_rename)\n _set_properties = staticmethod(dxpy.api.applet_set_properties)\n _add_tags = staticmethod(dxpy.api.applet_add_tags)\n _remove_tags = staticmethod(dxpy.api.applet_remove_tags)\n _close = staticmethod(_makeNonexistentAPIWrapper(\"/applet-xxxx/close\"))\n _list_projects = staticmethod(dxpy.api.applet_list_projects)\n\n def _new(self, dx_hash, **kwargs):\n '''\n :param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.\n :type dx_hash: dict\n :param runSpec: Run specification\n :type runSpec: dict\n :param dxapi: API version string\n :type dxapi: string\n :param inputSpec: Input specification (optional)\n :type inputSpec: dict\n :param outputSpec: Output specification (optional)\n :type outputSpec: dict\n :param access: Access specification (optional)\n :type access: dict\n :param title: Title string (optional)\n :type title: string\n :param summary: Summary string (optional)\n :type summary: string\n :param description: Description string (optional)\n :type description: string\n\n .. note:: It is highly recommended that the higher-level module\n :mod:`dxpy.app_builder` or (preferably) its frontend `dx build\n `_\n be used instead for applet creation.\n\n Creates an applet with the given parameters. See the API\n documentation for the `/applet/new\n `_\n method for more info. The applet is not run until :meth:`run()`\n is called.\n\n '''\n for field in 'runSpec', 'dxapi':\n if field not in kwargs:\n raise DXError(\"%s: Keyword argument %s is required\" % (self.__class__.__name__, field))\n dx_hash[field] = kwargs[field]\n del kwargs[field]\n for field in 'inputSpec', 'outputSpec', 'access', 'title', 'summary', 'description':\n if field in kwargs:\n dx_hash[field] = kwargs[field]\n del kwargs[field]\n\n resp = dxpy.api.applet_new(dx_hash, **kwargs)\n self.set_ids(resp[\"id\"], dx_hash[\"project\"])\n\n def get(self, **kwargs):\n \"\"\"\n :returns: Full specification of the remote applet object\n :rtype: dict\n\n Returns the contents of the applet. The result includes the\n key-value pairs as specified in the API documentation for the\n `/applet-xxxx/get\n `_\n method.\n \"\"\"\n return dxpy.api.applet_get(self._dxid, **kwargs)\n\n def run(self, applet_input, *args, **kwargs):\n \"\"\"\n Creates a new job that executes the function \"main\" of this applet with\n the given input *applet_input*.\n\n See :meth:`dxpy.bindings.dxapplet.DXExecutable.run` for the available\n args.\n \"\"\"\n # Rename applet_input arg to preserve API compatibility when calling\n # DXApplet.run(applet_input=...)\n return super(DXApplet, self).run(applet_input, *args, **kwargs)\n","sub_path":"src/python/dxpy/bindings/dxapplet.py","file_name":"dxapplet.py","file_ext":"py","file_size_in_byte":11953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"423702907","text":"import re\nfrom datetime import datetime, timedelta\n\nimport numpy as np\nimport pandas as pd\nimport tweepy\nimport xgboost as xgb\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import WordPunctTokenizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom telegram.ext import Filters, MessageHandler, Updater\n\nACC_TOKEN = 'XYZ'\nACC_SECRET = 'XYZ'\nCONS_KEY = 'XYZ'\nCONS_SECRET = 'XYZ'\n\nmodel = xgb.Booster() # init model\nmodel.load_model('sentiment.model') # load data\n\nstop = set(stopwords.words('english'))\nstemmer = SnowballStemmer(language='english')\ncv = CountVectorizer(max_features=100)\n\n\ndef authentication(cons_key, cons_secret, acc_token, acc_secret):\n auth = tweepy.OAuthHandler(cons_key, cons_secret)\n auth.set_access_token(acc_token, acc_secret)\n api = tweepy.API(auth)\n return api\n\n\ndef search_tweets(keyword, total_tweets):\n today_datetime = datetime.today().now()\n yesterday_datetime = today_datetime - timedelta(days=1)\n today_date = today_datetime.strftime('%Y-%m-%d')\n yesterday_date = yesterday_datetime.strftime('%Y-%m-%d')\n api = authentication(CONS_KEY, CONS_SECRET, ACC_TOKEN, ACC_SECRET)\n search_result = tweepy.Cursor(api.search,\n q=keyword,\n since=yesterday_date,\n result_type='recent',\n lang='en').items(total_tweets)\n return search_result\n\n\ndef clean_tweets(tweet):\n user_removed = re.sub(r'@[A-Za-z0-9]+', '', tweet)\n link_removed = re.sub('https?://[A-Za-z0-9./]+', '', user_removed)\n number_removed = re.sub('[^a-zA-Z]', ' ', link_removed)\n lower_case_tweet = number_removed.lower()\n tok = WordPunctTokenizer()\n words = tok.tokenize(lower_case_tweet)\n clean_tweet = (' '.join(words)).strip()\n return clean_tweet\n\n\ndef desc_clean(word):\n p1 = re.sub(pattern='(\\W+)|(\\d+)|(\\s+)', repl=' ', string=word)\n p1 = p1.lower()\n return p1\n\n\ndef sentiment(text):\n\n temporary = text\n text = text.map(desc_clean)\n text = [[x for x in x.split() if x not in stop] for x in text]\n text = [[stemmer.stem(x) for x in x] for x in text]\n text = [[x for x in x if len(x) > 2] for x in text]\n text = [' '.join(x) for x in text]\n text = cv.fit_transform(text).todense()\n combine_1 = pd.DataFrame(text)\n combine_1.rename(columns=lambda x: 'variable_' + str(x), inplace=True)\n test = xgb.DMatrix(combine_1)\n preds = model.predict(test)\n return preds\n\n\ndef analyze_tweets(keyword, total_tweets):\n score = 0\n tweets = search_tweets(keyword, total_tweets)\n tweet_list = []\n for tweet in tweets:\n tweet_list.append(tweet.text)\n tweet_list = np.array(tweet_list)\n preds = sentiment(pd.Series(tweet_list).astype(str))\n score = preds.mean()\n return score, preds\n\n\ndef send_the_result(bot, update):\n keyword = update.message.text\n print('User searched for', keyword)\n final_score, preds = analyze_tweets(keyword, 50)\n if final_score <= 0.4:\n status = 'NEGATIVE | ❌'\n elif final_score <= 0.5:\n status = 'NEUTRAL | 🔶'\n else:\n status = 'POSITIVE | ✅'\n bot.send_message(chat_id=update.message.chat_id,\n text='Average score for '\n + str(keyword)\n + ' is '\n + str(final_score)\n + ' | ' + status)\n print('Average score for '\n + str(keyword)\n + ' is '\n + str(final_score)\n + ' | ' + status)\n\ndef main():\n updater = Updater('556655323:AAGmIeWT0_0PHHmSz9yx-Ab-Ydw6VQPdfxs')\n dp = updater.dispatcher\n dp.add_handler(MessageHandler(Filters.text, send_the_result))\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"twitter_sentiment_analysis/tweet_sentiment.py","file_name":"tweet_sentiment.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"57421183","text":"import os, unittest, csv\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom pyvirtualdisplay import Display\nfrom selenium.common.exceptions import WebDriverException, NoSuchElementException\n\nimport requests\n\nclass TestEdaDealSite(unittest.TestCase):\n\n def setUp(self):\n self.display = Display(visible=0, size=(1024,800))\n self.display.start()\n\n self.current_path = os.path.dirname(os.path.realpath(__file__))\n self.chromedriver_path = os.path.join(self.current_path, 'chromedriver')\n self.driver = webdriver.Chrome(self.chromedriver_path)\n self.write_filename = 'output.csv'\n\n def test_get_offers_list(self):\n driver = self.driver\n driver.implicitly_wait(15)\n\n try:\n with open(self.write_filename, 'w', encoding='utf-8') as write_file:\n csv_writer = csv.writer(write_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\\n')\n col_names = ['Описание', 'Количество', 'Старая цена', 'Новая цена', 'Картинка', ]\n csv_writer.writerow([i.encode('utf8').decode('utf8') for i in col_names])\n\n for page in range(1, 250):\n try:\n page_url = 'https://edadeal.ru/naberezhnye-chelny/offers?page={}'.format(page)\n driver.get(page_url)\n elements = driver.find_elements_by_class_name('b-offer__root')\n for element in elements:\n image_url = element.find_element_by_class_name('b-image__img').get_attribute('src')\n request = requests.get(image_url, stream=True, timeout=40)\n filename = image_url.split(os.sep)[-1]\n with open(os.path.join('images', filename), 'wb') as image:\n image.write(request.content)\n try:\n description = element.find_element_by_class_name('b-offer__description').text\n except NoSuchElementException:\n description = ''\n try:\n quantity = element.find_element_by_class_name('b-offer__quantity').text\n except NoSuchElementException:\n quantity = ''\n try:\n price_old = element.find_element_by_class_name('b-offer__price-old').text\n except NoSuchElementException:\n price_old = ''\n try:\n price_new = element.find_element_by_class_name('b-offer__price-new').text\n except NoSuchElementException:\n price_new = ''\n\n csv_writer.writerow([description, quantity, price_old, price_new, filename])\n print('---> ', description)\n except NoSuchElementException:\n print('NoSuchElementException')\n except WebDriverException as err:\n print('Error is happened: <{}>'.format(str(err)))\n finally:\n driver.quit()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"get_offers_by_page.py","file_name":"get_offers_by_page.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"125675147","text":"\"\"\"\ntest list users\n\"\"\"\n\n# third-party\nimport pytest\n\n# local Django\nfrom django.contrib.auth.models import User\n\nfrom user.serializers import UserHeavySerializer\n\n# permitir acceso a db\npytestmark = [pytest.mark.django_db, pytest.mark.users_views]\n\n\n@pytest.mark.users_list\ndef test_get_all_user(admin_client):\n \"\"\"\n ...\n \"\"\"\n response = admin_client.get('/api/users/')\n serializer = UserHeavySerializer(\n User.objects.all(),\n many=True\n )\n assert response.status_code == 200\n assert serializer.data == response.data\n\n\n@pytest.mark.users_list\ndef test_list_users_only_for_super_users(staff_client):\n \"\"\"\n ...\n \"\"\"\n response = staff_client.get('/api/users/')\n assert response.status_code == 403\n","sub_path":"user/tests/user/test_user_list.py","file_name":"test_user_list.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"125388174","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 5 19:34:40 2017\n\n@author: Barry.Zhai\n\"\"\"\nimport tushare as ts\nimport pandas as pd\nimport time\n\n# main function\ndef main():\n \"\"\"\n should be turn on before open market\n do some initing and logging\n \"\"\"\n \n pass\n\n# merge current minute data into last minute's and get change percentage of price and volume index ratio\ndef merge_tdata(l_data, data):\n result = pd.merge(l_data.loc[:, ['code', 'trade', 'v_ma_base', 'volume']], data.drop('changepercent', 1), on = 'code', suffixes = ('_l', ''))\n result.loc[:, 'p_price'] = round(result['trade'] / result['trade_l'] - 1, 2)\n result = result.drop('trade_l', 1)\n \n result.loc[:, 'volume_diff'] = result['volume'] - result['volume_l']\n result.loc[:, 'v_ma'] = round(result['volume_diff'] / result['v_ma_base'], 2)\n result = result.drop(['volume_l', 'volume_diff'], 1)\n \n result.loc[:, 'p_open'] = round(result['open'] / result['settlement'],4) - 1\n result.loc[:, 'p_low'] = round(result['low'] / result['settlement'], 4) - 1\n \n return result\n\n# get volume index ratio base\ndef vol_index_base(data):\n \"\"\"\n base = last 5 days' volume amounts / 1200\n volume_index = this minute's volume / base\n \"\"\"\n result = data.copy()\n stocklist = list(result.code)\n result.loc[:, 'v_ma_base'] = 1\n for c in stocklist:\n try:\n hist = ts.get_hist_data(c)\n v_ma5 = hist.iloc[0].loc['v_ma5']\n base = v_ma5 / 240\n# print(c, 'base is', base)\n except:\n print(c, 'is not in get_hist_data, set base = 1')\n result.loc[result.code == c,'v_ma_base'] = base\n return result\n\n# determine if the stock has mass bid order\ndef mass_bid(code, start, end):\n source = ts.get_today_ticks(code)\n target = source[(source.time > start) & (source.time < end)]\n target.loc[:, 'p'] = round(target.change / target.price, 2)\n if len(target[target.p >= 0.001]) >= 3:\n return (code, 1)\n else:\n return (code, 0)\n \n# execution\ndef execution(code, amount, board, log = pd.DataFrame(columns = ['code', 'amount', 'time', 'status'])):\n board.loc[board.code == code, 'status'] += 1\n \n log_this = pd.DataFrame({'code': code, 'amount': amount, 'time': time.ctime(), 'status': board.loc[board.code == code, 'status']})\n log = pd.concat([log, log_this])\n \n return log \n \n# update dashboard\ndef dashboard(board, update):\n \"\"\"\n standard: \n 1. volume index ratio should be larger than 2\n 2. low price should be larger than 0.99 * last day's close price\n 3. open price should be larger than 0.99 * last day's close price and no more than 1.01 * last day's close price\n 4. p_price should be larger than 0.15\n 5. current == 1 no more than 5\n when status == 0,1,2,3 means it doesn't has signal, or been executed 1,2,3 times\n when status == 9 means it shouldn't be considered being bought this day\n when current == 0, it should hold still this minute,\n when current == 1, it should been tested mass_bid and executed this minute\n \"\"\"\n board_update = pd.merge(board, update, on = 'code')\n board_update.loc[:, 'current'] = 0\n board_update.loc[:, 'status_new'] = board_update['status']\n \n board_update.loc[(board_update.status == 0) & (board_update.p_open < -0.01 ), 'status_new'] = 9\n board_update.loc[(board_update.status == 0) & (board_update.p_open > 0.01 ), 'status_new'] = 9\n board_update.loc[(board_update.status == 0) & (board_update.p_low < -0.01 ), 'status_new'] = 9\n \n board_update.loc[(board_update.status != 3) & (board_update.status != 9) & (board_update.v_ma >= 2) & (board_update.p_price >= 0.015), 'current'] = 1\n \n board_change = board_update.loc[board_update.status_new != board_update.status, ['code', 'status', 'status_new']]\n board_update.loc[:, 'status'] = board_update['status_new']\n board_update = board_update.drop('status_new', 1)\n \n target = board_update.loc[board_update.current == 1]\n target = target.sort_values(['p_price', 'v_ma'], ascending = [False, False])\n target_list = list(target.code)\n if len(target_list) > 5:\n target_list = target_list[:5]\n \n return (board_update.loc[:, ['code', 'status']], target_list, board_change)\n ","sub_path":"daystrate.py","file_name":"daystrate.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"510929749","text":"#!/usr/bin/python\n\nimport sys\n\ntry:\n path = sys.argv[1]\n fp = open(path)\nexcept:\n print(\"Whoops\")\n exit()\n\nwidth = fp.readline()\nheight = fp.readline()\nname = fp.readline()\nimg = fp.readline().rstrip(\" };\\n\").split(',')\nprint(\" \")\nfor hex in img:\n h = int(hex.lstrip(), 16)\n print(\" {0:08b} \".format(h).replace('1','██').replace('0',' '))\nprint(\" \")\n","sub_path":"scripts/xbm_8x8_disp.py","file_name":"xbm_8x8_disp.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"621313436","text":"#!/usr/bin/python\n# Filename: NBA_utils.py\n# Some useful functions, put together by Tom Brummet\n\n# ============================================================================== #\n# #\n# (c) Copyright, 2013 University Corporation for Atmospheric Research (UCAR). #\n# All rights reserved. #\n# #\n# File: $RCSfile: fileheader,v $Tutils.py #\n# Version: $Revision: 1.0 $ Dated: $Date: 2013/10/10 14:44:18 $ #\n# #\n# ============================================================================== #\n\nfrom datetime import datetime\nimport sys\nimport os\nimport time\nimport calendar\nimport pandas as pd\nimport numpy as np\nimport Tutils\n\nHOME_TEAM = 'HomeTeam'\nHOME_TEAM_PTS = 'HomePoints'\nAWAY_TEAM = 'AwayTeam'\nAWAY_TEAM_PTS = 'AwayPoints'\n\nNCAA_NAME_MAP = {\n \"UC Santa Barb.\" : \"UC Santa Barbara\",\n \"Army West Point\" : \"Army\",\n \"Saint Joseph's\" : \"St. Josephs (PA)\",\n \"NC State\" : \"North Carolina State\",\n \"Ohio St.\" : \"Ohio State\",\n \"USC\" : \"Southern Cal\",\n \"Monmouth\" : \"Monmouth (NJ)\",\n \"St. Peter's\" : \"St. Peters\",\n \"Sacramento St.\" : \"CS Sacramento\",\n \"Montana St.\" : \"Montana State\",\n \"CSUN\" : \"CS Northridge\",\n \"Long Beach St.\" : \"CS Long Beach\",\n \"CSU Fullerton\" : \"CS Fullerton\",\n \"CSU Bakersfield\" : \"CS Bakersfield\", \n \"FIU\" : \"Florida Intl\",\n \"Saint Joseph's\" : \"St. Josephs (PA)\",\n \"LSU\" : \"Louisiana State\",\n \"UNI\" : \"Northern Iowa\",\n \"UNC-Greensboro\" : \"UNC Greensboro\",\n \"Eastern Wash.\" : \"Eastern Washington\",\n \"St. Mary's (Cal.)\" : \"St. Marys (CA)\"\n }\n\ndef read_OP_bball_dir(in_dir):\n \"\"\"\n Reads the OP_basketball_game dir into a pandas dataframe\n \"\"\"\n df = pd.DataFrame()\n \n # Get the dated subdirs\n num_files = 0\n files = os.listdir(in_dir)\n for f in files:\n file_path = \"%s\\%s\" % (in_dir, f)\n file_df = pd.read_csv(file_path)\n df = pd.concat([df, file_df])\n num_files += 1\n\n # Make sure we have home and away scores\n df = df[(np.isfinite(df['HomePoints']) &\n (np.isfinite(df['AwayPoints'])))]\n df.drop_duplicates(inplace=True) \n df.reset_index(inplace=True)\n print (\"Read %d files\" % num_files)\n return df\n\ndef read_odds_dir(odds_dir, file_base):\n \"\"\"\n Returns a pandas dataframe\n \"\"\"\n odds_df = pd.DataFrame()\n date_listing = os.listdir(odds_dir)\n num_files = 0\n for dt in date_listing:\n date_path = \"%s\\%s\" % (odds_dir, dt)\n file_listing = os.listdir(date_path) \n for f in file_listing:\n if not f.startswith(file_base):\n continue\n #print (\"Reading: %s\" % f)\n file_path = \"%s\\%s\" % (date_path, f)\n df = pd.read_csv(file_path)\n odds_df = pd.concat([odds_df, df])\n num_files += 1\n print (\"Read %d files\" % num_files)\n return odds_df\n\ndef remap_team_name(team_name):\n team = ''\n if team_name.find(\"Los Angeles Lakers\") != -1:\n team = \"L.A. Lakers\"\n elif team_name.find(\"Los Angeles Clippers\") != -1:\n team = \"L.A. Clippers\"\n elif team_name.find(\"Portland Trail Blazers\") != -1:\n team = \"Portland\"\n else: \n team = ' '.join(team_name.split()[:-1])\n return team\n\ndef remap_NCAA_team_name(team_name):\n \"\"\"\n \"\"\"\n if team_name in NCAA_NAME_MAP:\n return NCAA_NAME_MAP[team_name]\n else:\n return team_name\n\ndef add_odds(game_df, odds_df, league):\n \"\"\"\n \"\"\"\n predicted_spread_list = []\n predicted_over_under_list = []\n for ind, row in game_df.iterrows():\n if league=='NBA':\n home_team = remap_team_name(row[HOME_TEAM])\n away_team = remap_team_name(row[AWAY_TEAM])\n else:\n home_team = remap_NCAA_team_name(row[HOME_TEAM])\n away_team = remap_NCAA_team_name(row[AWAY_TEAM])\n\n game_day = row['EpochDt']\n\n game_odds = find_odds(odds_df, game_day, home_team, away_team)\n \n if (len(game_odds) > 0):\n # Retrieve the last odds that were recorded for this game\n predicted_points = game_odds['Over_under_VI Consensus'].tolist()[-1]\n predicted_spread = game_odds['Point_spread_VI Consensus'].tolist()[-1] \n\n predicted_spread_list.append(predicted_spread)\n predicted_over_under_list.append(predicted_points)\n else:\n predicted_spread_list.append(np.nan)\n predicted_over_under_list.append(np.nan)\n\n game_df['predicted_over_under'] = predicted_over_under_list\n game_df['predicted_spread'] = predicted_spread_list\n \n return\n \ndef find_odds(odds_df, game_date, home_team, away_team):\n #print (\"Looking for game\")\n #print (game_date, home_team, away_team)\n this_game_df = odds_df[((odds_df['Home_Team']==home_team) &\n (odds_df['Away_Team']==away_team) &\n (odds_df[\"GameDateEpoch\"]==game_date))].reset_index()\n\n # If the game doesn't exist\n #if len(this_game_df) == 0:\n # print (\"Can't find game %s %s %s\" % (Tutils.epoch2tme(game_date, \"%Y%m%d\"), home_team, away_team))\n #else:\n # print (\"Found Game, Returning odds\")\n #print (this_game_df)\n return (this_game_df.reset_index())\n\n# actual_df = pd.DataFrame()\n# for ind, row in this_game_df.iterrows():\n# odds_game_date = row['GameDateEpoch']\n# if odds_game_date == game_date:\n# #actual_df = pd.concat([actual_df, row])\n# actual_df = actual_df.append(row)\n\ndef get_team_over_under(game_df, team, home_team_str, away_team_str):\n \"\"\"\n Returns counts of over/unders for this team\n \"\"\"\n team_df = game_df[((game_df[home_team_str]==team) |\n (game_df[away_team_str]==team))]\n info_list = analyze_over_under(team_df)\n return (info_list)\n\n\ndef add_over_under_col(game_df, home_points_col, away_points_col, col_name): \n # Get count of how many games were over or under the spread\n under = 0\n over = 0\n perfect = 0\n skipped = 0\n new_col = []\n for ind, row in game_df.iterrows():\n if pd.isnull(row['predicted_over_under']):\n skipped += 1\n new_col.append(np.nan)\n continue\n if pd.isnull(row[home_points_col]) or pd.isnull(row[away_points_col]):\n skipped += 1\n new_col.append(np.nan)\n continue\n \n actual_points = row[home_points_col] + row[away_points_col]\n predicted_points = row['predicted_over_under']\n # If the modeled points were greater than the over under, AND more points\n # were scored than the over under, add a point\n if abs(actual_points) > abs(predicted_points):\n # If more points were scored than predicted \n over += 1\n new_col.append(1)\n # If the modeled points were less than the over under, AND less points\n # were scored than the over under, add a point \n elif abs(actual_points) < abs(predicted_points):\n # If less points were scored than predicted\n under += 1\n new_col.append(-1)\n elif (abs(actual_points) == abs(predicted_points)):\n # If the predicted points matched the game points perfectly\n perfect += 1\n new_col.append(0)\n else:\n skipped+=1\n new_col.append(np.nan)\n \n game_df[col_name] = new_col\n\n return (over, under, perfect, skipped)\n\n\ndef add_OU_HIT_col(game_df, home_points_col, away_points_col, col_name):\n \"\"\"\n \"\"\"\n hit = 0\n missed = 0\n perfect = 0\n skipped = 0\n new_col = []\n \"\"\"\n tmp_df = game_df.dropna(['predicted_over_under', home_points_col, away_points_col])\n tmp_df['avg_pts'] = tmp_df[home_points_col]+tmp_df[away_points_col]\n tmp_df['game_pts'] = tmp_df[HOME_TEAM_PTS] + tmp_df[AWAY_TEAM_PTS]\n hit = (len(tmp_df[(tmp_df['avg_pts'] > abs(tmp_df['predicted_over_under']) &\n tmp_df['game_pts'] > abs(tmp_df['predicted_over_under']))]) +\n len(tmp_df[(tmp_df['avg_pts'] < abs(tmp_df['predicted_over_under']) &\n tmp_df['game_pts'] < abs(tmp_df['predicted_over_under']))]) +))\n\n missed = (len(tmp_df[(tmp_df['avg_pts'] > abs(tmp_df['predicted_over_under']) &\n tmp_df['game_pts'] < abs(tmp_df['predicted_over_under']))]) +\n len(tmp_df[(tmp_df['avg_pts'] < abs(tmp_df['predicted_over_under']) &\n tmp_df['game_pts'] > abs(tmp_df['predicted_over_under']))]) +))\n perfect = (len(tmp_df['game_points']==abs(tmp_df['predicted_over_under'])))\n missed = len(tmp_df) - hit - missed - perfect\n \"\"\"\n for ind, row in game_df.iterrows():\n if pd.isnull(row['predicted_over_under']):\n skipped += 1\n new_col.append(np.nan)\n continue\n if pd.isnull(row[home_points_col]) or pd.isnull(row[away_points_col]):\n skipped += 1\n new_col.append(np.nan)\n continue\n avg_points = row[home_points_col] + row[away_points_col]\n game_points = row[HOME_TEAM_PTS] + row[AWAY_TEAM_PTS]\n predicted_points = abs(row['predicted_over_under'])\n if avg_points > predicted_points:\n if game_points > predicted_points:\n hit +=1\n new_col.append(1)\n elif game_points < predicted_points:\n missed += 1\n new_col.append(-1)\n else:\n perfect += 1\n new_col.append(0) \n elif avg_points < predicted_points:\n if game_points < predicted_points:\n hit += 1\n new_col.append(1)\n continue\n elif game_points > predicted_points:\n missed += 1\n new_col.append(-1)\n continue\n else:\n perfect += 1\n new_col.append(0)\n else:\n skipped += 1\n new_col.append(np.nan)\n \n game_df[col_name] = new_col\n\n return (hit, missed, perfect, skipped) \n \ndef add_over_under_col_threshold(game_df, home_points_col, away_points_col, col_name, threshold):\n \"\"\"\n Same as 'add_over_under_col' but only looks at games where\n the difference is over a certain threshold\n \"\"\"\n # Get count of how many games were over or under the spread\n under = 0\n over = 0\n perfect = 0\n skipped = 0\n new_col = []\n for ind, row in game_df.iterrows():\n #\n # If we are missing any of these fields, skip\n # \n if pd.isnull(row['predicted_over_under']):\n skipped += 1\n new_col.append(np.nan)\n continue\n if pd.isnull(row[home_points_col]) or pd.isnull(row[away_points_col]):\n skipped += 1\n new_col.append(np.nan)\n continue\n elif abs(row['predicted_over_under']) == 9999:\n skipped += 1\n new_col.append(np.nan)\n continue\n my_points = row[home_points_col] + row[away_points_col]\n predicted_points = abs(row['predicted_over_under'])\n #\n # If there is a posative threshold --\n # ignore all cases where the avg was less than predicted+threshold\n #\n if threshold > 0:\n# if ((abs(my_points) < (predicted_points + threshold)) or\n# (abs(my_points) > (predicted_points + threshold+2))):\n if (abs(my_points) < (predicted_points + threshold)): \n skipped += 1\n new_col.append(np.nan)\n continue\n #\n # If there is a negative threshold --\n # ignore all cases where the avg was more than predicted+threshold\n #\n else:\n #if ((abs(my_points) > (predicted_points + threshold)) or\n # (abs(my_points) < (predicted_points + threshold-2))):\n if (abs(my_points) > (predicted_points + threshold)):\n skipped += 1\n new_col.append(np.nan)\n continue\n game_points = row[HOME_TEAM_PTS] + row[AWAY_TEAM_PTS]\n if abs(game_points) > predicted_points:\n # If more points were scored than predicted \n over += 1\n new_col.append(1)\n elif abs(game_points) < predicted_points:\n # If less points were scored than predicted\n under += 1\n new_col.append(-1)\n else:\n # If the predicted points matched the game points perfectly\n perfect += 1\n new_col.append(0)\n\n game_df[col_name] = new_col\n\n return (over, under, perfect, skipped)\n\ndef add_PS_col_threshold(game_df, home_points_col, away_points_col, col_name, threshold):\n \"\"\"\n Same as 'add_over_under_col' but only looks at games where\n the difference is over a certain threshold -- POINT SPREAD\n \"\"\"\n # Get count of how many games were over or under the spread\n hit = 0\n miss = 0\n perfect = 0\n skipped = 0\n new_col = []\n for ind, row in game_df.iterrows():\n #\n # If we are missing any of these fields, skip\n # \n if pd.isnull(row['predicted_spread']):\n skipped += 1\n new_col.append(np.nan)\n continue\n if pd.isnull(row[home_points_col]) or pd.isnull(row[away_points_col]):\n skipped += 1\n new_col.append(np.nan)\n continue\n elif abs(row['predicted_spread'])==9999:\n skipped += 1\n new_col.append(np.nan)\n continue\n my_spread = row[away_points_col]-row[home_points_col]\n predicted_spread = row['predicted_spread']\n actual_spread = row[AWAY_TEAM_PTS] - row[HOME_TEAM_PTS]\n #\n # Ignore all cases where my PS doesn't differ from the given PS by more than threshold\n #\n if abs(my_spread - predicted_spread) < threshold:\n skipped += 1\n new_col.append(np.nan)\n continue\n #\n # Check to see if I hit or miss\n #\n if ((my_spread > predicted_spread) and\n (actual_spread > predicted_spread)):\n hit += 1\n new_col.append(1)\n elif ((my_spread < predicted_spread) and\n (actual_spread < predicted_spread)):\n hit += 1\n new_col.append(1)\n elif (actual_spread == predicted_spread):\n perfect += 1\n new_col.append(0)\n else:\n miss += 1\n new_col.append(-1)\n\n game_df[col_name] = new_col \n return (hit, miss, perfect, skipped)\n\ndef print_over_under(over, under, perfect, skipped):\n print (\"---------------------------------------\")\n print (\"Num times more points were scored than predicted: %d\" % over)\n print (\"Num times less points were scored than predicted: %d\" % under)\n print (\"Num times vegas predicted the score perfectly: %d\" % perfect)\n print (\"Num games couldn't find odds for: %d\" % skipped)\n print (\"---------------------------------------\") \n\n\ndef analyze_over_under(game_df): \n # Get count of how many games were over or under the spread\n skipped = len(game_df[pd.isnull(game_df['Over_Under_HIT'])]==True)\n under = len(game_df[game_df['Over_Under_HIT']==-1])\n over = len(game_df[game_df['Over_Under_HIT']==1])\n perfect = len(game_df[game_df['Over_Under_HIT']==0])\n \n return (over, under, perfect, skipped)\n\ndef get_odds_dt(row):\n year = Tutils.epoch2tme(row['Time'], \"%Y\")\n dt_str = row['Game_Time'].split()\n (mon,day) = dt_str[0].split(\"/\")\n #if int(mon) > 6:\n # year = int(year)-1\n out_str = \"%s%s%s\" % (year, mon, day)\n return Tutils.tme2epoch(out_str, \"%Y%m%d\")\n\ndef add_odds_game_date(odds_df):\n \"\"\"\n \"\"\"\n odds_df[\"GameDateEpoch\"] = odds_df.apply(lambda row: get_odds_dt(row), axis=1)\n return\n\ndef make_team_df_map(game_df):\n \"\"\"\n \"\"\"\n team_df_map = {}\n all_teams = game_df[HOME_TEAM].append(game_df[AWAY_TEAM]).unique().tolist()\n for tm in all_teams:\n team_df_map[tm] = game_df[((game_df[HOME_TEAM]==tm) |\n (game_df[AWAY_TEAM]==tm))].sort_values('EpochDt').reset_index(drop=True)\n return team_df_map\n\ndef get_prior_game_avg(row, base_df, lookback_games):\n # Get prior games for this team\n team_df = base_df[((base_df[\"Team\"] == row[\"Team\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n if len(team_df) == 0:\n return np.nan\n elif len(team_df) < lookback_games:\n return np.nan\n else:\n # Return the most recent value\n last_ind = len(team_df) - lookback_games\n return team_df.iloc[-3:][\"PointsScored\"].mean()\n \n \ndef print_threshold_counts(home_col, away_col, threshold, game_df, col_name):\n \"\"\"\n Prints how many times the 'home_col'+'away_col' beat the predicted based on the threshold\n \"\"\"\n #\n # Check O/U when teams are averaging more than thshld points over the spread\n #\n this_info = add_over_under_col_threshold(game_df, home_col, away_col,\n (\"OU_HIT_%s_%d\" % (col_name, threshold)),\n threshold)\n print (\"NUM GAMES AVG OVER/UNDERS WHEN AVG > spread+%d: %s\" % (threshold, col_name))\n print_over_under(this_info[0], this_info[1], this_info[2], this_info[3])\n if this_info[0]+this_info[1]==0:\n oo_pct = np.nan\n oo_count = np.nan\n elif this_info[1] == 0:\n #oo_pct = 5\n oo_pct = 1 \n oo_count = this_info[0]+this_info[1] \n else:\n #oo_pct = this_info[0]/this_info[1]\n oo_pct = this_info[0]/(this_info[0]+this_info[1])\n oo_count = this_info[0]+this_info[1]\n #\n # Check O/U when teams are averaging thshld points less than the spread\n #\n this_info = add_over_under_col_threshold(game_df, home_col, away_col,\n (\"OU_HIT_%s_%d\" % (col_name, -threshold)),\n -threshold)\n print (\"NUM GAMES AVG OVER/UNDERS WHEN AVG < spread-%d: %s\" % (threshold, col_name)) \n print_over_under(this_info[0], this_info[1], this_info[2], this_info[3])\n if this_info[0]+this_info[1]==0:\n uu_pct = np.nan\n uu_count = np.nan\n elif this_info[0] == 0:\n #uu_pct = 5\n uu_pct = 1\n uu_count = this_info[0]+this_info[1] \n else:\n #uu_pct = this_info[1]/this_info[0]\n uu_pct = this_info[1]/(this_info[0]+this_info[1])\n uu_count = this_info[1]+this_info[0]\n\n return (oo_pct, oo_count, uu_pct, uu_count)\n\ndef print_PS_threshold_counts(home_col, away_col, threshold, game_df, col_name):\n \"\"\"\n Prints how many times the 'home_col'+'away_col' beat the predicted based on the threshold\n \"\"\"\n #\n # Check O/U when teams are averaging more than thshld points over the spread\n #\n this_info = add_PS_col_threshold(game_df, home_col, away_col,\n (\"PS_HIT_%s_%d\" % (col_name, threshold)),\n threshold)\n print (\"NUM GAMES AVG OVER/UNDERS WHEN AVG > spread+%d: %s\" % (threshold, col_name))\n print_over_under(this_info[0], this_info[1], this_info[2], this_info[3])\n if this_info[0]+this_info[0]==0:\n hit_pct = np.nan\n hit_count = np.nan\n elif this_info[1] == 0:\n #oo_pct = 5\n hit_pct = 1 \n hit_count = this_info[0]\n else:\n #oo_pct = this_info[0]/this_info[1]\n hit_pct = this_info[0]/(this_info[0]+this_info[1])\n hit_count = this_info[0]\n miss_count = this_info[1]\n miss_pct = 1-hit_pct\n \n return (hit_pct, hit_count, miss_pct, miss_count)\n\n\ndef get_bball_epoch_dt(row):\n game_date_str = str(int(row['GameTime']))\n return Tutils.tme2epoch(game_date_str, \"%Y%m%d\")\n \ndef get_prior_score(row, base_df, lookback_games):\n \"\"\"\n Used to create ML models, requires 'team' and 'gameTime' (seconds)\n NOTE : COULD BE MERGED WITH 'GET_PRIOR_SCORE_GAME_DF'\n \"\"\"\n # Get prior games for this team\n team_df = base_df[((base_df[\"Team\"] == row[\"Team\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n if len(team_df) == 0:\n return np.nan\n elif len(team_df) < lookback_games:\n return np.nan\n else:\n # Return the most recent value\n last_ind = len(team_df) - lookback_games\n return team_df.loc[last_ind][\"PointsScored\"]\n\ndef get_prior_score_game_df(row, base_df, team_col, ht_col, at_col, tim_col, lookback_games):\n \"\"\"\n Used to create ML models, used for the 'game_df' created from the OP_basketball_games_dir\n NOTE : COULD BE MERGED WITH 'GET_PRIOR_SCORE'\n \"\"\"\n if lookback_games==0:\n if row[team_col] == row[ht_col]:\n return row['HomePoints']\n else:\n return row['AwayPoints']\n \n # Get prior games for this team\n team_df = base_df[((base_df[ht_col] == row[team_col]) |\n (base_df[at_col] == row[team_col]))]\n if len(team_df) == 0:\n return np.nan\n \n # Get only the previous games\n sorted_team_df = team_df[(team_df[\"EpochDt\"] < row[tim_col])].sort_values(\"EpochDt\").reset_index()\n if len(sorted_team_df) < lookback_games:\n return np.nan\n \n last_ind = len(sorted_team_df) - lookback_games\n last_game_row = sorted_team_df.loc[last_ind]\n \n if last_game_row[ht_col] == row[team_col]:\n return last_game_row['HomePoints']\n else:\n return last_game_row['AwayPoints'] \n\ndef calculate_team_avg_past_xdays_game_df(team_name, num_games, row, team_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] < row['EpochDt']][-num_games:]\n # If there aren't at least x games, return missing\n if len(last_x_games) < num_games:\n return np.nan\n team_points = []\n for i, rw in last_x_games.iterrows():\n if rw['AwayTeam'] == team_name:\n team_points.append(rw['AwayPoints'])\n elif rw['HomeTeam'] == team_name:\n team_points.append(rw['HomePoints'])\n return (sum(team_points)/len(team_points))\n\ndef calculate_team_avg_xdays_game_df(team_name, num_games, row, team_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] <= row['EpochDt']][-num_games:]\n # If there aren't at least x games, return missing\n if len(last_x_games) < num_games:\n return np.nan\n team_points = []\n for i, rw in last_x_games.iterrows():\n if rw['AwayTeam'] == team_name:\n team_points.append(rw['AwayPoints'])\n elif rw['HomeTeam'] == team_name:\n team_points.append(rw['HomePoints'])\n return (sum(team_points)/len(team_points))\n\n\ndef calculate_team_avg_past_xdays_base_df(row, base_df, lookback_games):\n \"\"\"\n \"\"\"\n # Get the last x games\n team_df = base_df[((base_df[\"Team\"] == row[\"Team\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n # If there aren't at least x games, return missing\n if len(team_df) < lookback_games:\n return np.nan\n return (team_df[-lookback_games:][\"PointsScored\"].mean())\n\ndef calculate_opp_team_allowed_avg_past_xdays_base_df(row, base_df, lookback_games):\n \"\"\"\n \"\"\"\n # Get the last x games\n team_df = base_df[((base_df[\"Team\"] == row[\"OppTeam\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n # If there aren't at least x games, return missing\n if len(team_df) < lookback_games:\n return np.nan\n return (team_df[-lookback_games:][\"OppPointsScored\"].mean())\n\ndef calculate_team_rest_base_df(row, base_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n team_df = base_df[((base_df[\"Team\"] == row[\"Team\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n if len(team_df) == 0:\n return np.nan\n game_time = row[\"GameTime\"]\n last_game_time = team_df.iloc[-1][\"GameTime\"]\n rest = round((game_time - last_game_time) / 86400)\n return rest\n\ndef calculate_opp_team_rest_base_df(row, base_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n team_df = base_df[((base_df[\"Team\"] == row[\"OppTeam\"]) &\n (base_df[\"GameTime\"] < row[\"GameTime\"]))].sort_values(\"GameTime\").reset_index()\n if len(team_df) == 0:\n return np.nan\n game_time = row[\"GameTime\"]\n last_game_time = team_df.iloc[-1][\"GameTime\"]\n rest = round((game_time - last_game_time) / 86400)\n return rest\n\ndef calculate_team_rest_game_df(team_name, row, team_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] < row['EpochDt']]\n if len(last_x_games) == 0:\n return np.nan\n game_time = row['EpochDt']\n last_game_time = last_x_games.iloc[-1][\"EpochDt\"]\n rest = round((game_time - last_game_time) / 86400)\n return rest\n\ndef calculate_current_team_rest_game_df(team_name, row, team_df, this_epch):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] <= row['EpochDt']]\n if len(last_x_games) == 0:\n return np.nan\n last_game_time = last_x_games.iloc[-1][\"EpochDt\"]\n rest = round((this_epch - last_game_time) / 86400)\n return rest\n\ndef calculate_team_allowed_avg_past_xdays_game_df(team_name, num_games, row, team_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] < row['EpochDt']][-num_games:]\n # If there aren't at least x games, return missing\n if len(last_x_games) < num_games:\n return np.nan\n team_points = []\n for i, rw in last_x_games.iterrows():\n if rw['AwayTeam'] == team_name:\n team_points.append(rw['HomePoints'])\n elif rw['HomeTeam'] == team_name:\n team_points.append(rw['AwayPoints'])\n return (sum(team_points)/len(team_points))\n\ndef calculate_team_allowed_avg_xdays_game_df(team_name, num_games, row, team_df):\n \"\"\"\n \"\"\"\n # Get the last x games\n last_x_games = team_df[team_df['EpochDt'] <= row['EpochDt']][-num_games:]\n # If there aren't at least x games, return missing\n if len(last_x_games) < num_games:\n return np.nan\n team_points = []\n for i, rw in last_x_games.iterrows():\n if rw['AwayTeam'] == team_name:\n team_points.append(rw['HomePoints'])\n elif rw['HomeTeam'] == team_name:\n team_points.append(rw['AwayPoints'])\n return (sum(team_points)/len(team_points))\n\n\ndef analyze_point_spreads(game_df):\n \"\"\"\n \"\"\"\n # Get a count of the times vegas was over the spread and under\n OS = 0\n US = 0\n avg_error = []\n for ind, row in game_df.iterrows():\n if pd.isnull(row['predicted_spread']):\n continue\n elif abs(row['predicted_spread'])==9999:\n continue\n adjusted_home_points = row['HomePoints']+row['predicted_spread']\n if (adjusted_home_points > row['AwayPoints']):\n OS += 1\n else:\n US += 1\n avg_error.append(abs(adjusted_home_points - row['AwayPoints']))\n print (avg_error[-1])\n print (\"Num Times spread was too high: %d\" % OS)\n print (\"Num Times spread was too low: %d\" % US)\n print (\"Avg Error: %f\" % (sum(avg_error)/len(avg_error)))\n \n\ndef check_mult_var_OU_counts(var1, var2, game_df, value, new_col_name):\n \"\"\"\n Looks at all cases where var1 AND var2 say 'value' and see how they compare vs the over under\n \"\"\"\n hit = 0\n miss = 0\n perfect = 0\n new_col = []\n for ind, row in game_df.iterrows():\n # Skip mising rows\n if pd.isnull(row[var1]) or pd.isnull(row[var2]) or pd.isnull(row['Over_Under_HIT']):\n new_col.append(np.nan)\n continue\n # If both columns hit their value, it is a hit\n if row[var1] == value and row[var2] == value:\n new_col.append(1)\n hit += 1\n elif row[var1] == 0 and row[var2] == 0:\n new_col.append(0)\n perfect += 1 \n else:\n new_col.append(-1)\n miss += 1\n\n game_df[new_col_name] = new_col\n if hit == 0:\n hit_pct = 0\n else:\n hit_pct = (hit / (hit + miss))\n miss_pct = 1-hit_pct\n return (hit_pct, hit, miss_pct, miss)\n\ndef get_team_win_sum_base_df(row, base_df, team):\n \"\"\"\n \"\"\"\n team_df = base_df[((base_df['Team']==team) &\n (base_df['GameTime'] rw['OppPointsScored']:\n win_loss += 1\n else:\n win_loss -= 1 \n return win_loss\n\ndef get_team_win_sum_game_df(row, game_df, team):\n \"\"\"\n \"\"\"\n team_home_df = game_df[((game_df['HomeTeam']==team) &\n (game_df['EpochDt'] rw['AwayPoints']:\n win_loss += 1\n else:\n win_loss -= 1 \n\n for ind, rw in team_away_df.iterrows():\n if rw['AwayPoints'] > rw['HomePoints']:\n win_loss += 1\n else:\n win_loss -= 1 \n\n return win_loss\n\ndef get_team_current_win_sum_game_df(row, game_df, team):\n \"\"\"\n \"\"\"\n team_home_df = game_df[((game_df['HomeTeam']==team) &\n (game_df['EpochDt']<=row['EpochDt']))]\n team_away_df = game_df[((game_df['AwayTeam']==team) &\n (game_df['EpochDt']<=row['EpochDt']))] \n \n win_loss = 0\n for ind, rw in team_home_df.iterrows():\n if rw['HomePoints'] > rw['AwayPoints']:\n win_loss += 1\n else:\n win_loss -= 1 \n\n for ind, rw in team_away_df.iterrows():\n if rw['AwayPoints'] > rw['HomePoints']:\n win_loss += 1\n else:\n win_loss -= 1 \n\n return win_loss\n\ndef calc_team_win_sum_base_df(base_df):\n \"\"\"\n \"\"\"\n team_map = {}\n all_teams = base_df['Team'].unique().tolist()\n for tm in all_teams:\n tm_games = base_df[base_df['Team']==tm]\n win_loss = 0\n for ind, row in tm_games.iterrows():\n if row['PointsScored'] > row['OppPointsScored']:\n win_loss += 1\n else:\n win_loss -= 1 \n team_map[tm] = win_loss\n \n return team_map\n\ndef calc_team_win_sum_game_df(game_df):\n \"\"\"\n \"\"\"\n team_map = {}\n all_teams = pd.unique(game_df[['HomeTeam','AwayTeam']].values.ravel('K')).tolist()\n for tm in all_teams:\n win_loss = 0 \n tm_home_games = game_df[game_df['HomeTeam']==tm]\n tm_away_games = game_df[game_df['AwayTeam']==tm] \n for ind, row in tm_home_games.iterrows():\n if row['HomePoints']>row['AwayPoints']:\n win_loss+=1\n else:\n win_loss-=1 \n for ind, row in tm_away_games.iterrows():\n if row['AwayPoints'] > row['HomePoints']:\n win_loss += 1\n else:\n win_loss -= 1 \n team_map[tm] = win_loss\n \n return team_map\n","sub_path":"scripts/python/NBA_utils.py","file_name":"NBA_utils.py","file_ext":"py","file_size_in_byte":32058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"298533518","text":"import math\r\nimport numpy as np\r\nfrom ConvLSTM import ConvLSTM\r\nfrom data import data2\r\n\r\n\r\ndef get_random_block_from_data(data, batch_size):\r\n start_index = np.random.randint(0, len(data) - batch_size)\r\n return data[start_index: start_index + batch_size]\r\n\r\n\r\nbatch_size = 32\r\ntimesteps = 3\r\nshape = [4, 7]\r\nchannels = 3\r\nkernel = [2, 2]\r\nfilters = 3\r\nsteps = 1000\r\n\r\nConvLSTM = ConvLSTM(batch_size=batch_size, timesteps=timesteps, shape=shape, channels=channels, kernel=kernel, filters=filters, learning_rate=0.001)\r\n\r\n# data3是去除了不需要的属性的数据,形状是(len, 168, 6)\r\ndata3 = np.empty((len(data2), 168, 6))\r\nfor i in range(len(data2)):\r\n data3[i] = np.delete(data2[i], [0, 1, 5], axis=1)\r\n data3[:, [0, 1, 2, 3, 4, 5]] = data3[:, [5, 4, 3, 0, 1, 2]]\r\n\r\ninput_data = np.empty((len(data3), 6, 4, 7, 3))\r\n\r\nfor i in range(len(data3)):\r\n t = 0\r\n for j in range(6):\r\n temp = np.empty(84)\r\n for m in range(28):\r\n temp[m] = data3[i][t][3]\r\n temp[m + 28] = data3[i][t][4]\r\n temp[m + 28 + 28] = data3[i][t][5]\r\n t += 1\r\n input_data[i][j] = np.reshape(temp, [4, 7, 3])\r\n\r\ny_total = np.empty((1000, 2))\r\nt = 0\r\nfor i in range(steps):\r\n batch = get_random_block_from_data(input_data, batch_size)\r\n batch_x = np.delete(batch, [3, 4, 5], axis=1)\r\n batch_y = np.delete(batch, [0, 1, 2], axis=1)\r\n cost = ConvLSTM.opt(batch_x, batch_y)\r\n if(i%3 == 0):\r\n y_total[t][0] = t + 1\r\n y_total[t][1] = math.log(cost)\r\n t = t + 1\r\n print(cost)\r\n\r\n# np.savetxt(' y_total.csv', y_total, delimiter = ',')\r\n# print(cost)\r\n","sub_path":"convlstm/criteo/TOTAL.py","file_name":"TOTAL.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"443367286","text":"\"\"\"Defines the Matrix class\"\"\"\nfrom scipy.sparse import coo_matrix # type: ignore\nimport numpy as np\nfrom pyNastran.op2.op2_interface.write_utils import export_to_hdf5\nfrom pyNastran.utils import object_attributes, object_methods\nfrom pyNastran.op2.op2_interface.op2_codes import MSC_ELEMENTS\n\n\nclass Matrix:\n \"\"\"\n Defines a Matrix object that's stored in op2.matrices\n\n Attributes\n ----------\n name : str\n the name of the matrix\n data : varies\n dense : np.ndarray\n sparse : coo_matrix\n data is initialized by setting the matrix.data attribute externally\n is_matpool : bool\n is this a matpool matrix\n\n \"\"\"\n def __init__(self, name, form, is_matpool=False):\n \"\"\"\n Initializes a Matrix\n\n Parameters\n ----------\n name : str\n the name of the matrix\n form : int\n the matrix type\n is_matpool : bool\n is this a matpool matrix\n\n +------+-----------------+\n | Form | Meaning |\n +======+=================+\n | 1 | Square |\n | 2 | Rectangular |\n | 6 | Symmetric |\n | 9 | Pseudo identity |\n +------+-----------------+\n\n \"\"\"\n self.name = name\n self.data = None\n self.form = form\n self.is_matpool = is_matpool\n\n # only exist for is_matpool = True\n self.col_nid = None\n self.col_dof = None\n self.row_nid = None\n self.row_dof = None\n if not isinstance(name, str):\n raise TypeError('name=%r must be a string; type=%s' % (name, type(name)))\n\n @property\n def shape_str(self):\n \"\"\"gets the matrix description\"\"\"\n if self.form == 0:\n return 'N/A'\n if self.form == 1:\n return 'square'\n elif self.form == 2:\n return 'rectangular'\n elif self.form == 6:\n return 'symmetric'\n elif self.form == 9:\n return 'pseudo-identity'\n else:\n raise RuntimeError('form = %r' % self.form)\n\n def export_to_hdf5(self, group, log):\n \"\"\"exports the object to HDF5 format\"\"\"\n export_to_hdf5(self, group, log)\n\n def build_dataframe(self):\n \"\"\"exports the object to pandas format\"\"\"\n import pandas as pd\n matrix = self.data\n if matrix is None:\n return\n if isinstance(matrix, coo_matrix):\n data = {'row': matrix.row, 'col': matrix.col, 'data' : matrix.data}\n data_frame = pd.DataFrame(data=data).reindex(columns=['row', 'col', 'data'])\n elif isinstance(matrix, np.ndarray):\n data_frame = pd.DataFrame(data=matrix)\n else:\n raise NotImplementedError(type(matrix))\n self.data_frame = data_frame\n\n def write(self, mat, print_full=True):\n \"\"\"writes to the F06\"\"\"\n mat.write(np.compat.asbytes(str(self) + '\\n'))\n\n matrix = self.data\n if self.data is None:\n skip_msg = 'skipping %s because data is None\\n\\n' % self.name\n mat.write(skip_msg.encode('ascii'))\n return\n if isinstance(matrix, coo_matrix):\n if print_full:\n for row, col, value in zip(matrix.row, matrix.col, matrix.data):\n mat.write(np.compat.asbytes(\"(%i, %i) %s\\n\" % (row, col, value)))\n else:\n mat.write(str(matrix))\n else:\n mat.write(np.compat.asbytes('name=%r; shape=%s; form=%i; Type=%r\\n' % (\n self.name, str(self.data.shape).replace('L', ''),\n self.form, self.shape_str)))\n if print_full:\n np.savetxt(mat, self.data, fmt='%.18e', delimiter=',')\n #f06.write(str(matrix))\n #print('WARNING: matrix type=%s does not support writing' % type(matrix))\n mat.write(np.compat.asbytes('\\n\\n'))\n\n def object_attributes(self, mode='public', keys_to_skip=None):\n if keys_to_skip is None:\n keys_to_skip = []\n\n my_keys_to_skip = [\n 'object_methods', 'object_attributes',\n ]\n return object_attributes(self, mode=mode, keys_to_skip=keys_to_skip+my_keys_to_skip)\n\n def object_methods(self, mode='public', keys_to_skip=None):\n if keys_to_skip is None:\n keys_to_skip = []\n my_keys_to_skip = []\n\n my_keys_to_skip = [\n 'object_methods', 'object_attributes',\n ]\n return object_methods(self, mode=mode, keys_to_skip=keys_to_skip+my_keys_to_skip)\n\n def __repr__(self):\n header = 'Matrix[%r];' % self.name\n if self.data is None:\n shape = 'data=None; '\n class_name = ''\n dtype = '; '\n else:\n class_name = str(type(self.data)).replace('', '').replace(\"'\", '') + ';'\n shape = ' shape=%s;' % str(self.data.shape).replace('L', '')\n dtype = '%s;' % self.data.dtype\n msg = '%-18s %-18s type=%-33s dtype=%-10s desc=%s' % (\n header, shape, class_name, dtype, self.shape_str)\n return msg\n\n\nclass MatrixDict:\n \"\"\"storage object for KDICT, MDICT, BDICT, etc. is op2.matdicts\"\"\"\n def __init__(self, name):\n self.name = name\n self.element_types = []\n self.numwides = []\n self.numgrids = []\n self.dof_per_grids = []\n\n self.eids = []\n self.ge = []\n self.address = []\n self.forms = []\n self.sils = []\n self.xforms = []\n\n def add(self, eltype, numwids, numgrid, dof_per_grid, form,\n eids, ge, address, sil, xform=None):\n \"\"\"Sets the next set of the KDICT\"\"\"\n self.element_types.append(eltype)\n self.numwides.append(numwids)\n self.numgrids.append(numgrid)\n self.dof_per_grids.append(dof_per_grid)\n self.forms.append(form)\n\n self.eids.append(eids)\n self.ge.append(ge)\n self.address.append(address)\n self.sils.append(sil)\n self.xforms.append(xform)\n\n #@property\n #def nodes(self):\n #return [sil // 10 for sil in self.sils]\n\n #@property\n #def dofs(self):\n #return [sil % 10 for sil in self.sils]\n\n @property\n def nelements(self):\n return sum([len(eids) for eids in self.eids])\n\n @property\n def element_names(self):\n return [MSC_ELEMENTS[etype] for etype in self.element_types]\n\n def __repr__(self):\n msg = 'MatrixDict(name=%r, nelements=%s element_types=%s, element_names=[%s])' % (\n self.name, self.nelements, self.element_types, ', '.join(self.element_names))\n return msg\n","sub_path":"pyNastran/op2/result_objects/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"153322623","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/nailixing/PyProjects/nusdb_rafiki/singa_auto/model/utils.py\n# Compiled at: 2020-04-24 21:27:49\n# Size of source mod 2**32: 5496 bytes\nimport os, sys, uuid, platform\nfrom typing import Type\nfrom importlib import import_module\nfrom pkg_resources import parse_version\nimport pickle\nfrom singa_auto.constants import ModelDependency\nfrom .model import BaseModel\nfrom .dataset import DatasetUtils\nfrom .log import LoggerUtils\n\nclass InvalidModelClassError(Exception):\n pass\n\n\ndef load_model_class(model_file_bytes, model_class, temp_mod_name=None) -> Type[BaseModel]:\n temp_mod_name = temp_mod_name or '{}-{}'.format(model_class, str(uuid.uuid4()))\n temp_model_file_name = '{}.py'.format(temp_mod_name)\n with open(temp_model_file_name, 'wb') as (f):\n f.write(model_file_bytes)\n try:\n try:\n import time\n time.sleep(3)\n mod = import_module(temp_mod_name)\n clazz = getattr(mod, model_class)\n except Exception as e:\n raise InvalidModelClassError(e)\n\n finally:\n os.remove(temp_model_file_name)\n\n return clazz\n\n\ndef parse_model_install_command(dependencies, enable_gpu=False):\n conda_env = os.environ.get('CONDA_ENVIORNMENT')\n commands = []\n for dep, ver in dependencies.items():\n if dep == ModelDependency.KERAS:\n commands.append('pip --no-cache-dir install Keras=={}'.format(ver))\n elif dep == ModelDependency.TORCH:\n commands.append('pip --no-cache-dir install torch=={}'.format(ver))\n elif dep == ModelDependency.TORCHVISION:\n commands.append('pip --no-cache-dir install torchvision=={}'.format(ver))\n elif dep == ModelDependency.SCIKIT_LEARN:\n commands.append('pip --no-cache-dir install scikit-learn=={}'.format(ver))\n elif dep == ModelDependency.TENSORFLOW:\n if enable_gpu:\n commands.append('pip --no-cache-dir install tensorflow-gpu=={}'.format(ver))\n else:\n commands.append('pip --no-cache-dir install tensorflow=={}'.format(ver))\n else:\n if dep == ModelDependency.SINGA:\n options = '-y -c nusdbsystem'\n if conda_env is not None:\n options += ' -n {}'.format(conda_env)\n if enable_gpu:\n commands.append('conda install {} singa-gpu={}'.format(options, ver))\n else:\n commands.append('conda install {} singa-cpu={}'.format(options, ver))\n else:\n if dep == ModelDependency.DS_CTCDECODER:\n commands.append('pip --no-cache-dir install {}'.format(parse_ctc_decoder_url(ver)))\n else:\n commands.append('pip --no-cache-dir install {}=={}'.format(dep, ver))\n\n return '; '.join(commands)\n\n\ndef parse_ctc_decoder_url(ver):\n is_arm = 'arm' in platform.machine()\n is_mac = 'darwin' in sys.platform\n is_64bit = sys.maxsize > 2147483647\n is_ucs2 = sys.maxunicode < 1114111\n if is_arm:\n ctc_arch = 'arm64' if is_64bit else 'arm'\n else:\n if is_mac:\n ctc_arch = 'osx'\n else:\n ctc_arch = 'cpu'\n ctc_arch += '-ctc'\n plat = platform.system().lower()\n arch = platform.machine()\n if plat == 'linux':\n if arch == 'x86_64':\n plat = 'manylinux1'\n if plat == 'darwin':\n plat = 'macosx_10_10'\n version_string = ver.strip()\n ds_version = parse_version(version_string)\n branch = 'v{}'.format(version_string)\n m_or_mu = 'mu' if is_ucs2 else 'm'\n pyver = ''.join(map(str, sys.version_info[0:2]))\n artifact = 'ds_ctcdecoder-{ds_version}-cp{pyver}-cp{pyver}{m_or_mu}-{platform}_{arch}.whl'.format(ds_version=ds_version,\n pyver=pyver,\n m_or_mu=m_or_mu,\n platform=plat,\n arch=arch)\n deepspeech_scheme = 'https://index.taskcluster.net/v1/task/project.deepspeech.deepspeech.native_client.%(branch_name)s.%(arch_string)s/artifacts/public/%(artifact_name)s'\n return deepspeech_scheme % {'arch_string':ctc_arch, 'artifact_name':artifact, 'branch_name':branch}\n\n\ndef deserialize_knob_config(knob_config_bytes):\n knob_config = pickle.loads(knob_config_bytes.encode())\n return knob_config\n\n\ndef serialize_knob_config(knob_config):\n knob_config_bytes = pickle.dumps(knob_config, 0).decode()\n return knob_config_bytes\n\n\nclass ModelUtils:\n\n def __init__(self):\n self._trial_id = None\n self.dataset = DatasetUtils()\n self.logger = LoggerUtils()\n\n\nutils = ModelUtils()\nlogger = utils.logger\ndataset = utils.dataset","sub_path":"pycfiles/singa_auto-0.2.0-py2.py3-none-any/utils.cpython-36.py","file_name":"utils.cpython-36.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"263891793","text":"from numba.pycc import CC\ncc = CC('board_ocr')\ncc.verbose = True\nimport numpy as np\n\n@cc.export('parseImage2', 'uint8[:,:](uint8[:,:,:],uint8[:],uint8[:])')\ndef parseImage2(img,color1,color2):\n\n black = np.array((10,10,10), dtype=np.uint8)\n white = np.array((240,240,240), dtype=np.uint8)\n \n colors = [black,white,color1,color2]\n \n result = np.zeros((20,10),dtype=np.uint8)\n \n for x in range(10):\n for y in range(20):\n pix = img[y,x]\n closest = 0\n lowest_dist = (256*256)*3\n i = 0\n for color in colors:\n dist = ((color[0] - pix[0]) * (color[0] - pix[0]) +\n (color[1] - pix[1]) * (color[1] - pix[1]) +\n (color[2] - pix[2]) * (color[2] - pix[2]))\n if dist < lowest_dist:\n lowest_dist = dist\n closest = i\n i += 1\n \n result[y,x] = closest\n \n return result\n \nif __name__ == '__main__':\n cc.compile()","sub_path":"OCRAlgo/buildBoardOCR2.py","file_name":"buildBoardOCR2.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"560270168","text":"import keras\r\nimport numpy as np\r\nfrom keras.backend import expand_dims, sum\r\nfrom keras.activations import tanh, softmax\r\n\r\n\"\"\" Custom layer that implements an attention mechanism, for use with LSTM layers \r\n\r\n@:param units: The number of units in the layer. Should be set equal to the\r\n window size used by the preceding LSTM layer\r\n \r\n@:note: Input should be a list containing (1) the output of the preceding\r\n LSTM layer, and (2) the hidden state of the preceding LSTM layer.\r\n\"\"\"\r\n\r\nclass Attention(keras.layers.Layer):\r\n\r\n def __init__(self, units, **kwargs):\r\n super(Attention, self).__init__(**kwargs)\r\n self.output_dim = units\r\n\r\n def build(self, input_shape):\r\n self.W1 = keras.layers.Dense(self.output_dim, name=\"Attention_W1\")\r\n self.W2 = keras.layers.Dense(self.output_dim, name=\"Attention_W2\")\r\n self.V = keras.layers.Dense(1, name=\"Attention_final\")\r\n super().build(input_shape)\r\n\r\n def call(self, inputs, training=None, mask=None):\r\n # Uses standard LSTM notation: c is output states, h is hidden states\r\n c = inputs[0]\r\n h = inputs[1]\r\n hidden_with_time_axis = expand_dims(h, 1)\r\n score = tanh(self.W1(c) + self.W2(hidden_with_time_axis))\r\n attention_weights = softmax(self.V(score), axis=1)\r\n context_vector = attention_weights * c\r\n context_vector = sum(context_vector, axis=1, keepdims=False)\r\n\r\n return context_vector\r\n\r\n def compute_output_shape(self, input_shape):\r\n return input_shape[1]\r\n\r\n def get_config(self):\r\n base_config = super().get_config()\r\n config = {'units': self.output_dim}\r\n return dict(list(base_config.items()) + list(config.items()))\r\n","sub_path":"Attention.py","file_name":"Attention.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"577344894","text":"# classifier.py\n\nimport tensorflow as tf\n\nimport configs\n\nfrom tensorflow.keras.layers import Conv2D, Dense, Flatten\n\n\nclass Classifier(tf.keras.Model):\n\n def __init__(self):\n super(Classifier, self).__init__(name='Classifier')\n self.conv1 = Conv2D(filters=32, kernel_size=(3, 3), strides=(2, 2),\n activation='relu')\n self.conv2 = Conv2D(filters=32, kernel_size=(3, 3), strides=(2, 2),\n activation='relu')\n self.flatten = Flatten()\n self.dense1 = Dense(units=configs.num_classes, activation='softmax')\n\n def call(self, inputs):\n x = self.conv1(inputs)\n x = self.conv2(x)\n x = self.flatten(x)\n predictions = self.dense1(x)\n return predictions\n","sub_path":"models/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"51082896","text":"favorite_languages = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'ruby',\n 'phil': 'python',\n}\n\nresponders = list(favorite_languages.keys())[:]\nresponders.append('john')\nresponders.append('carl')\nresponders.append('jessica')\n\nfor name in responders:\n if name.lower() in favorite_languages.keys():\n print(name + ' already respondent.')\n else:\n print(name + ' can respond now!')","sub_path":"ch6/quest.py","file_name":"quest.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"261536238","text":"from __future__ import print_function\nfrom flask import request, Blueprint\nfrom launcher import pdb2pqr_runner, apbs_runner\nimport os, sys\n\ntesk_proxy = Blueprint('tesk_proxy', __name__)\n\nPDB2PQR_BUILD_PATH = os.environ.get('PDB2PQR_BUILD_PATH')\nSTORAGE_HOST = os.environ.get('STORAGE_HOST', 'http://localhost:5001')\nTESK_HOST = os.environ.get('TESK_HOST', 'http://localhost:5001')\n\nif PDB2PQR_BUILD_PATH is not None:\n sys.path.append(PDB2PQR_BUILD_PATH)\n\n@tesk_proxy.route('/', methods=['GET'])\n@tesk_proxy.route('/check/', methods=['GET'])\ndef liveness():\n \"\"\"Probes server to check if alive\"\"\"\n return '', 200\n\n@tesk_proxy.route('/api/tesk//', methods=['GET', 'POST'])\ndef submit_tesk_action(job_id, task_name):\n response = None\n http_status = None\n\n if request.method == 'GET':\n pass\n elif request.method == 'POST':\n '''\n Handler for using the TESK service.\n '''\n if task_name.lower() in ['apbs', 'pdb2pqr']:\n if task_name == 'apbs':\n if 'infile' in request.args.to_dict() and request.args['infile'].lower() == 'true':\n infile_name = request.json['filename']\n runner = apbs_runner.Runner(STORAGE_HOST, job_id=job_id, infile_name=infile_name)\n redirectURL = runner.start(STORAGE_HOST, TESK_HOST)\n else:\n form = request.json\n for key in form.keys():\n # unravels output parameters from form\n if key == 'output_scalar':\n for option in form[key]:\n form[option] = option\n form.pop('output_scalar')\n elif not isinstance(form[key], str):\n form[key] = str(form[key])\n\n runner = apbs_runner.Runner(STORAGE_HOST, job_id=job_id, form=form)\n redirectURL = runner.start(STORAGE_HOST, TESK_HOST)\n\n elif task_name == 'pdb2pqr':\n pass\n form = request.json\n runner = pdb2pqr_runner.Runner(form, request.files, STORAGE_HOST, job_id=job_id)\n redirectURL = runner.start(STORAGE_HOST, TESK_HOST)\n\n\n\n response = {\n 'message': \"Task type '%s' accepted. Beginning execution\" % (task_name),\n 'jobURL': redirectURL\n }\n http_status = 202\n\n else:\n response = {\n 'error': \"task type '%s' does not exist or is not implemented\" % (task_name)\n }\n http_status = 404\n \n # import pprint as pp\n # pp.pprint(response)\n\n sys.stdout.flush()\n return response, http_status","sub_path":"src/tesk/tesk_proxy/service/tesk_proxy_service.py","file_name":"tesk_proxy_service.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"431585894","text":"\n# coding: utf-8\n# (C) 2019 yoshida121. All rights reserved.\n\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nimport os\n\nclass GoogleDriveUpload():\n \"\"\" PythonからGoogleDriveへとファイルをアップロードする \"\"\"\n def __init__(self, child_folder=None):\n \"\"\"\n Parameters:\n child_folder : 子ディレクトリに認証ファイルが存在する場合に指定\n \"\"\"\n if child_folder is not None:\n os.chdir(\"./\" + str(child_folder) + \"/\")\n auth = GoogleAuth()\n auth.CommandLineAuth()\n # print(os.getcwd)\n self.drive = GoogleDrive(auth)\n if child_folder is not None:\n os.chdir(\"./../\")\n \n def upload(self, file_name, parents_id=None, print_data=False, check_fold=True):\n \"\"\"\n ファイルをGoogleDriveへとアップロードする\n\n Parameters:\n file_name : アップロードするファイル名\n print_data : アップロードしたファイルのファイル名とIDを取得する\n check_fold : \n \"\"\"\n id = None\n\n if \".csv\" in file_name: \n # 自身の環境に合わせてmimeTypeを増やしてください. 下記のURLにMIMEの一覧あり\n # http://www.geocities.co.jp/Hollywood/9752/mime.html\n # https://developers.google.com/drive/api/v3/mime-types\n mimeType = \"text/csv\"\n elif \".txt\" in file_name:\n mimeType = \"text/plain\"\n elif os.path.isdir(file_name):\n mimeType = \"application/vnd.google-apps.folder\"\n else:\n mimeType = None\n\n if os.path.isdir(file_name) and check_fold:\n title, id = self.upload(file_name, print_data=True, check_fold=False)\n # print(id)\n os.chdir(file_name)\n up_file_list = os.listdir()\n for up_file in up_file_list:\n temp_title, temp_id = self.upload(up_file, print_data=True, parents_id=id)\n os.chdir(\"../\")\n return None, None\n\n print(\"ID :\", id)\n if parents_id is None and id is None:\n parents_id = \"root\"\n \n # print(mimeType)\n print(parents_id)\n file = self.drive.CreateFile({\"title\": file_name, \"mimeType\": mimeType, \"parents\": [{\"id\": parents_id}]})\n if mimeType != \"application/vnd.google-apps.folder\":\n file.SetContentFile(file_name)\n print(\"Uploadeing...\")\n file.Upload()\n print(\"Complete!\")\n if print_data:\n print(\"-------------------------------\")\n print(\"File Name :\", file[\"title\"])\n print(\"File ID :\", file[\"id\"])\n print(\"-------------------------------\")\n return file[\"title\"], file[\"id\"]\n return \n\n","sub_path":"Uploader.py","file_name":"Uploader.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"56156087","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 18 10:52:34 2017\n\n@author: Aeolitus\n\"\"\"\nimport Objekte\nimport DatenbankEditWaffeneigenschaft\nfrom PyQt5 import QtWidgets, QtCore\n\nclass DatenbankEditWaffeneigenschaftWrapper(object):\n def __init__(self, datenbank, waffeneigenschaft=None, readonly = False):\n super().__init__()\n self.datenbank = datenbank\n if waffeneigenschaft is None:\n waffeneigenschaft = Objekte.Waffeneigenschaft()\n self.waffeneigenschaftPicked = waffeneigenschaft\n self.nameValid = True\n self.readonly = readonly\n waffeneigenschaftDialog = QtWidgets.QDialog()\n self.ui = DatenbankEditWaffeneigenschaft.Ui_waffeneigenschaftDialog()\n self.ui.setupUi(waffeneigenschaftDialog)\n \n if not waffeneigenschaft.isUserAdded:\n if readonly:\n self.ui.warning.setText(\"Gelöschte Elemente können nicht verändert werden.\")\n self.ui.warning.setVisible(True)\n\n waffeneigenschaftDialog.setWindowFlags(\n QtCore.Qt.Window |\n QtCore.Qt.CustomizeWindowHint |\n QtCore.Qt.WindowTitleHint |\n QtCore.Qt.WindowCloseButtonHint)\n \n self.ui.nameEdit.setText(waffeneigenschaft.name)\n self.ui.nameEdit.textChanged.connect(self.nameChanged)\n self.nameChanged()\n\n self.ui.textEdit.setPlainText(waffeneigenschaft.text)\n self.ui.scriptPrioEdit.setValue(waffeneigenschaft.scriptPrio)\n\n scriptPrioDoc = [\n \"Die Skript-Priorität legt die Reihenfolge der Auswertung fest. 0 ist Standard, negative Werte werden davor,\",\n \"positive Werte danach ausgewertet. Dies ist relevant, falls bspw. die INI verdoppelt werden soll nachdem\",\n \"Kampfreflexe eingerechnet wurde. In diesem Fall sollte die Skript-Priorität höher als die von Kampfreflexe sein.\"\n ]\n\n self.ui.scriptPrioEdit.setToolTip(\"\\n\".join(scriptPrioDoc))\n\n self.ui.scriptEdit.setText(waffeneigenschaft.script)\n\n self.ui.scriptEdit.setToolTip(\"Siehe ScriptAPI.md im Installationsordner für verfügbare Funktionen und Beispiele.\")\n\n waffeneigenschaftDialog.show()\n ret = waffeneigenschaftDialog.exec_()\n if ret == QtWidgets.QDialog.Accepted:\n self.waffeneigenschaft = Objekte.Waffeneigenschaft()\n self.waffeneigenschaft.name = self.ui.nameEdit.text()\n self.waffeneigenschaft.text = self.ui.textEdit.toPlainText()\n\n self.waffeneigenschaft.scriptPrio = self.ui.scriptPrioEdit.value()\n self.waffeneigenschaft.script = str.strip(self.ui.scriptEdit.text())\n\n self.waffeneigenschaft.isUserAdded = False\n if self.waffeneigenschaft == self.waffeneigenschaftPicked:\n self.waffeneigenschaft = None\n else:\n self.waffeneigenschaft.isUserAdded = True\n else:\n self.waffeneigenschaft = None\n \n def nameChanged(self):\n name = self.ui.nameEdit.text()\n if name == \"\":\n self.ui.nameEdit.setToolTip(\"Name darf nicht leer sein.\")\n self.ui.nameEdit.setStyleSheet(\"border: 1px solid red;\")\n self.nameValid = False\n elif name != self.waffeneigenschaftPicked.name and name in self.datenbank.waffeneigenschaften:\n self.ui.nameEdit.setToolTip(\"Name existiert bereits.\")\n self.ui.nameEdit.setStyleSheet(\"border: 1px solid red;\")\n self.nameValid = False\n else:\n self.ui.nameEdit.setToolTip(\"\")\n self.ui.nameEdit.setStyleSheet(\"\")\n self.nameValid = True\n self.updateSaveButtonState()\n\n def updateSaveButtonState(self):\n self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Save).setEnabled(not self.readonly and self.nameValid)","sub_path":"DatenbankEditWaffeneigenschaftWrapper.py","file_name":"DatenbankEditWaffeneigenschaftWrapper.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"494546383","text":"from kruskal import *\nfrom common import *\n\ndef test_kruskal_min_span_tree():\n E = {\n 'a': {'b': 4, 'h': 8},\n 'c': {'b': 8, 'd': 7, 'f': 4},\n 'd': {'f': 14},\n 'e': {'d': 9, 'f': 10},\n 'g': {'f': 2},\n 'h': {'b': 11, 'g': 1, 'i': 7},\n 'i': {'c': 2, 'g': 6},\n }\n\n V = set()\n for start, ends in E.items():\n for end, _ in ends.items():\n V.add(start)\n V.add(end)\n V = {c:Node(key=None, value=c) for c in V}\n overall_weight, minimum_edges = kruskal(E, V)\n assert overall_weight == 37\n\n","sub_path":"clrs/tests/test_kruskal.py","file_name":"test_kruskal.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"433958418","text":"import numpy as np\nimport renom as rm\nfrom renom_img import __version__\nfrom renom_img.api.cnn import CnnBase\nfrom renom_img.api.utility.exceptions.exceptions import WeightLoadError\n\n\nclass DarknetConv2dBN(rm.Model):\n\n def __init__(self, channel, filter=3, prev_ch=None):\n pad = int((filter - 1) / 2)\n if prev_ch is not None:\n self._conv = rm.Conv2d(channel=channel, filter=filter, padding=pad)\n self._conv.params = {\n \"w\": rm.Variable(self._conv._initializer((channel, prev_ch, filter, filter)), auto_update=True),\n \"b\": rm.Variable(np.zeros((1, channel, 1, 1), dtype=np.float32), auto_update=False),\n }\n self._bn = rm.BatchNormalize(momentum=0.1, mode='feature')\n else:\n self._conv = rm.Conv2d(channel=channel, filter=filter, padding=pad)\n self._bn = rm.BatchNormalize(momentum=0.1, mode='feature')\n\n def forward(self, x):\n\n return rm.leaky_relu(self._bn(self._conv(x)), 0.1)\n\n\nclass Darknet19Base(rm.Model):\n\n def __init__(self):\n self.block1 = rm.Sequential([\n DarknetConv2dBN(32, prev_ch=3),\n rm.MaxPool2d(filter=2, stride=2)\n ])\n self.block2 = rm.Sequential([\n DarknetConv2dBN(64, prev_ch=32),\n rm.MaxPool2d(filter=2, stride=2)\n ])\n self.block3 = rm.Sequential([\n DarknetConv2dBN(128, prev_ch=64),\n DarknetConv2dBN(64, filter=1, prev_ch=128),\n DarknetConv2dBN(128, prev_ch=64),\n rm.MaxPool2d(filter=2, stride=2)\n ])\n self.block4 = rm.Sequential([\n DarknetConv2dBN(256, prev_ch=128),\n DarknetConv2dBN(128, filter=1, prev_ch=256),\n DarknetConv2dBN(256, prev_ch=128),\n rm.MaxPool2d(filter=2, stride=2)\n ])\n self.block5 = rm.Sequential([\n DarknetConv2dBN(512, prev_ch=256),\n DarknetConv2dBN(256, filter=1, prev_ch=512),\n DarknetConv2dBN(512, prev_ch=256),\n DarknetConv2dBN(256, filter=1, prev_ch=512),\n DarknetConv2dBN(512, prev_ch=256),\n ])\n self.block6 = rm.Sequential([\n # For concatenation.\n rm.MaxPool2d(filter=2, stride=2),\n DarknetConv2dBN(1024, prev_ch=512),\n DarknetConv2dBN(512, filter=1, prev_ch=1024),\n DarknetConv2dBN(1024, prev_ch=512),\n DarknetConv2dBN(512, filter=1, prev_ch=1024),\n DarknetConv2dBN(1024, prev_ch=512),\n ])\n\n def forward(self, x):\n h = self.block1(x)\n h = self.block2(h)\n h = self.block3(h)\n h = self.block4(h)\n f = self.block5(h)\n h = self.block6(f)\n return h, f\n\n\nclass CnnYolov2(CnnBase):\n\n WEIGHT_URL = \"http://renom.jp/docs/downloads/weights/{}/detection/Yolov2.h5\".format(__version__)\n\n def __init__(self, weight_decay=None):\n super(CnnYolov2, self).__init__()\n self.class_map = None\n self.num_anchor = None\n self._base = Darknet19Base()\n self._conv1 = rm.Sequential([\n DarknetConv2dBN(channel=1024, prev_ch=1024),\n DarknetConv2dBN(channel=1024, prev_ch=1024),\n ])\n self._conv21 = DarknetConv2dBN(channel=64, prev_ch=512, filter=1)\n self._conv2 = DarknetConv2dBN(channel=1024, prev_ch=1024 + 256)\n self._last = rm.Conv2d(channel=self.output_size, filter=1)\n\n for part in [self._conv21, self._conv1, self._conv2]:\n for layer in part.iter_models():\n if not layer.params:\n continue\n if isinstance(layer, rm.Conv2d):\n layer.params = {\n \"w\": rm.Variable(layer._initializer(layer.params.w.shape), auto_update=True),\n \"b\": rm.Variable(np.zeros_like(layer.params.b), auto_update=False),\n }\n elif isinstance(layer, rm.BatchNormalize):\n layer.params = {\n \"w\": rm.Variable(layer._initializer(layer.params.w.shape), auto_update=True),\n \"b\": rm.Variable(np.zeros_like(layer.params.b), auto_update=True),\n }\n\n def set_output_size(self, out_size, class_map, num_anchor):\n self.class_map = class_map\n self.num_anchor = num_anchor\n self.output_size = out_size\n self._last._channel = out_size\n self._last.params = {\n \"w\": rm.Variable(self._last._initializer((self.output_size, 1024, 1, 1)), auto_update=True),\n \"b\": rm.Variable(self._last._initializer((1, self.output_size, 1, 1)), auto_update=False),\n }\n\n def load_pretrained_weight(self, path):\n try:\n self._base.load(path)\n except:\n raise WeightLoadError(\n 'The pretrained weights path {} can not be loaded into the class {}.'.format(path, self.__class__))\n\n def reset_deeper_layer(self):\n pass\n\n def set_anchor(self, anchor_size):\n self.num_anchor = anchor_size\n\n def forward(self, x):\n self._base.set_auto_update(self.train_whole)\n self._base.set_models(inference=(not self.train_whole or getattr(self, 'inference', False)))\n h, f = self._base(x)\n f = self._conv21(f)\n h = self._conv1(h)\n\n h = self._conv2(rm.concat(h, rm.concat([f[:, :, i::2, j::2]\n for i in range(2) for j in range(2)])))\n out = self._last(h)\n\n # Create yolo format.\n N, C, H, W = h.shape\n\n reshaped = out.reshape(N, self.num_anchor, -1, W * H)\n conf = rm.sigmoid(reshaped[:, :, 0:1]).transpose(0, 2, 1, 3)\n px = rm.sigmoid(reshaped[:, :, 1:2]).transpose(0, 2, 1, 3)\n py = rm.sigmoid(reshaped[:, :, 2:3]).transpose(0, 2, 1, 3)\n pw = rm.exp(reshaped[:, :, 3:4]).transpose(0, 2, 1, 3)\n ph = rm.exp(reshaped[:, :, 4:5]).transpose(0, 2, 1, 3)\n cl = rm.softmax(reshaped[:, :, 5:].transpose(0, 2, 1, 3))\n return rm.concat(conf, px, py, pw, ph, cl).transpose(0, 2, 1, 3).reshape(N, -1, H, W)\n","sub_path":"renom_img/api/cnn/yolo_v2.py","file_name":"yolo_v2.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"641404572","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\n\n\nclass purchase_order_info(osv.osv_memory):\n\n _name = \"purchase.order.info\"\n _description = \"Purchase Order Info\"\n\n _columns = {\n 'pr_line_id': fields.many2one('purchase.requisition.line', 'Purchase Requisition Line', readonly=True),\n 'po_info_line': fields.one2many('purchase.order.info.line', 'po_info_id', 'Purchase Order Info Lines', readonly=True)\n }\n _defaults = {\n 'pr_line_id': lambda self, cr, uid, ctx: ctx.get('active_id', False)\n }\n\n def onchange_pr_line_id(self, cr, uid, ids, pr_line_id, context=None):\n pr_line = self.pool.get('purchase.requisition.line').browse(cr, uid, pr_line_id)\n po_info_line = []\n for line in pr_line.po_line_ids:\n po_info_line.append([0, 0, {\n 'order_id': line.order_id and line.order_id.id or False,\n 'partner_id': line.partner_id and line.partner_id.id or False,\n 'state': line.state,\n }])\n return {'value': {\n 'po_info_line': po_info_line,\n }}\n\npurchase_order_info()\n\n\nclass purchase_order_info_line(osv.osv_memory):\n\n STATE_SELECTION = [\n ('draft', 'Draft'),\n ('confirmed', 'Confirmed'),\n ('done', 'Done'),\n ('cancel', 'Cancelled')\n ]\n\n _name = \"purchase.order.info.line\"\n _description = \"Purchase Order Info Lines\"\n\n _columns = {\n 'po_info_id': fields.many2one('purchase.order.info', 'Purchase Order Info'),\n 'order_id': fields.many2one('purchase.order', 'Purchase Order'),\n 'partner_id': fields.many2one('res.partner', 'Supplier'),\n 'state': fields.selection(STATE_SELECTION, 'Status')\n }\n\npurchase_order_info_line()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"ecosoft-addons/purchase_requisition_multi_supplier/wizard/purchase_order_info.py","file_name":"purchase_order_info.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"465971819","text":"\n\ndef es_primo(num):\n for x in range(2, num):\n if num % x == 0:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n while 1:\n try:\n num = int(input(\"numero: \"))\n except:\n print(\"ingrese numero\")\n else:\n break\n \n if es_primo(num):\n print(\"el numero es primo\")\n else:\n print(\"el numero no es primo\")\n","sub_path":"57031-porollan-santiago/tp1/ej6.py","file_name":"ej6.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"161822482","text":"\nfrom utilities import setup_logger\n\nimport pymongo\nimport json\nimport logging\n\n#function to trim hedaers, works with EMS_ONLINE_STATUS, 'EMS_STATUS', 'EMS_CONFIGURATION'\nmessage_type = ['EMS_ONLINE_STATUS', 'EMS_STATUS', 'EMS_CONFIGURATION', 'EMS_EVENT_LIST']\nheaders1 = ['Data_%s_Events_' %typestr for typestr in message_type]\nheaders2 = ['Message_', 'Header_', 'Data_']\n\n\n\n#create a mongo client\nclient = pymongo.MongoClient(\"localhost\", 27017)\n\n#use the client to connect to a database\ndbconstage = client.AutServer_Emscommslog_Stage\n\ndbcontest = client.AutServer_Emscommslog_Test\n\n\n#file logger\ncleaninglog = setup_logger('dbinsert_logger', 'cleaninglog.log')\n\n\ndef replace_str(keystr):\n for fld1 in headers1:\n if fld1 in keystr:\n keystr = keystr.replace(fld1, '')\n for fld2 in headers2:\n if fld2 in keystr:\n keystr = keystr.replace(fld2, '')\n keystr = keystr.replace('Attributes_Attribute__', '')\n keystr = keystr.replace('Locations_Location', 'Locations')\n keystr = keystr.replace('ONLINE_STATUS', 'OnlineStatus')\n keystr = keystr.replace('CONFIGURATION_', '')\n keystr = keystr.replace('EMC_EVENT_REQUEST_SearchCriteria_','')\n keystr = keystr.replace('FMC_MODIFY_FAULT_', '')\n keystr = keystr.replace('AUT_SYSTEM_LOGIN_INFORMATION_SystemLoginInformation_', '')\n return keystr\n\n\ndef flatten_json(y):\n \"\"\"Flatten Json files in send EMS Log Messages\"\"\"\n out = {}\n\n def flatten(x, name=''):\n if type(x) is dict:\n for a in x:\n flatten(x[a], name + a + '_')\n elif type(x) is list and type(x[0]) is dict:\n i = 0\n for row in x:\n if 'Name' in row and \"Value\" in row:\n dx = [(row['Name'], row['Value'])]\n flatten(dict(dx), name + '_') \n \n else:\n flatten(row, name + str(i) + '_')\n i += 1\n \n else:\n out[name[:-1]] = x\n\n flatten(y)\n return out\n\n\ndef extract_clean_ems_sendlogs(dbconn):\n \"\"\"query mongodb and flatten the output into a dictionary\"\"\"\n \n query = {\"Finename\":{\"$gte\":\"EMSComms.log.2018-08-29-00\", \"$lt\":\"EMSComms.log.2018-08-30-00\"}}\n \n samp = dbconn.find(query, {\"Message.@xmlns:xsi\":0, \n \"Message.@xsi:noNamespaceSchemaLocation\":0},\n no_cursor_timeout=True).skip(0).limit(500000)\n\n dictlist = []\n for inp in samp:\n newdic = {}\n flat = flatten_json(inp)\n for key in flat:\n newkey = replace_str(key)\n newdic[newkey] = flat[key]\n\n dictlist.append(newdic)\n return dictlist\n\n\ndef preprocess_eventlist(dictlist):\n \"\"\"Preporecess eventlist, by building a list of dict for \n events\"\"\"\n\n out = []\n for doc in dictlist:\n ups = {}\n lk = []\n \n #go through keys and build a list of dict for events \n for key, value in doc.items():\n\n dicts = {}\n\n if key.startswith('Event'):\n val = 0\n #single events, have no event number, check and add number\n try:\n val = int(key.split(\"_\")[1])\n eventnum = \"_\".join(key.split(\"_\")[:2])\n newk = \"_\".join(key.split(\"_\")[2:])\n except ValueError:\n eventnum = key.split(\"_\")[:1][0] +\"_0\" \n newk = \"_\".join(key.split(\"_\")[1:])\n\n dicts['EventNum'] = eventnum\n dicts[newk] = value\n\n lk.append(dicts)\n else:\n ups[key] = value\n \n #now build the list of dict for events\n eventslist = list(set([pos.get('EventNum') for pos in lk]))\n eventdict = {evnt: {} for evnt in eventslist}\n\n for dx in lk:\n if dx['EventNum'] in eventdict:\n eventdict[dx['EventNum']].update(dx)\n\n #eventdict_list_values = list(eventdict.values())\n ups['Events'] = list(eventdict.values())\n \n out.append(ups) \n #print(out)\n return out\n\n\ndef insert_one(messages, collection_obj, collection_name):\n \n for mesg in messages:\n print(mesg['Finename'])\n #filter according to collection\n if mesg['idd'].split(\"|\")[0] == collection_name:\n print(\"Inserting message: %s\" % str(mesg['_id']))\n \n try:\n collection_obj.insert_one(mesg)\n out = \"Success inserting: %s\" % str(mesg['_id'])\n #cleaninglog.info(out)\n print(out)\n except Exception as e:\n error = 'Error inserting: %s %s' %(mesg['_id'], str(e))\n cleaninglog.error(error)\n print(error)\n print(\" \")\n\n\nif __name__ == \"__main__\":\n dbases = ['EmsConfiguration', 'EmsOnlineStatus', 'EmsStatus', 'EmsEventList'] \n #dbases = ['EmsEventList']\n #dbases = ['EmsStatus']\n dbases += ['AutSystemLoginInformation','EmcAcknowledgeEvents','EmcEventRequest','EmcEventUnsubscribe']\n dbases += ['EmcPrompt','EmcSyncRequest','FmcFaultUnsubscribe','FmcModifyFault']\n\n\n # #file processing worked, make connection to collection and insert send messages\n #for collections in dbases: #use for send messages\n \n for collections in dbases:\n dbcollectionstage_obj = dbconstage[collections]\n \n clean_dictlist = []\n dictlist = []\n \n print(\"connected to %s collection\" %collections)\n try:\n dictlist = extract_clean_ems_sendlogs(dbcollectionstage_obj)\n cleaninglog.info(\"Success reading: %s\" % (collections))\n print(\"Sucess reading %s\" % (collections))\n \n except Exception as e:\n cleaninglog.error(\"Error reading: %s %s\" % (collections, str(e)))\n print(str(e))\n else:\n #if eventlist, pre-processing with this\n if collections == \"EmsEventList\":\n try: \n \n clean_dictlist = preprocess_eventlist(dictlist)\n print(\"Sucess preprocessing: %s\" % (collections))\n except Exception as error1:\n cleaninglog.error(\"Error reading: %s %s\" % (collections, str(error1)))\n else:\n clean_dictlist = dictlist\n \n if clean_dictlist:\n\n dbcollectiontest_obj = dbcontest[collections]\n insert_one(clean_dictlist, dbcollectiontest_obj, collections)\n \n ","sub_path":"clean_emslogs_sendmsg.py","file_name":"clean_emslogs_sendmsg.py","file_ext":"py","file_size_in_byte":6584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"88233124","text":"\n\nclass Cycle:\n\tdef __init__(self, filename):\n\t\t# Well now I guess I need to figure out how to reda this file...\n\t\tfile = open(filename, 'r')\n\t\tself.filename = filename\n\t\tline = file.readline()\n\t\tself.metadata = list()\n\t\twhile not \"TABLE\" in line:\n\t\t\tattr_array = line.split(\"\\t\")\n\t\t\tif len(attr_array) > 3:\n\t\t\t\telements = {}\n\t\t\t\telements[\"varname\"] = attr_array[0]\n\t\t\t\telements[\"type\"] = attr_array[1]\n\t\t\t\telements[\"data\"] = attr_array[2]\n\t\t\t\telements[\"name\"] = attr_array[len(attr_array) - 1]\n\t\t\t\tself.metadata.append(elements)\n\t\t\tline = file.readline()\n\n\t\ttemp_table = \"\"\n\t\tself.labels = file.readline().split(\"\\t\")\n\t\tself.datatypes = file.readline().split(\"\\t\")\n\n\t\tline = file.readline()\n\t\twhile not \"TABLE\" in line:\n\t\t\ttemp_table += line + '\\n'\n\t\t\tline = file.readline()\n\n\t\trows = temp_table.split(\"\\n\")\n\t\t#converts the data to 2D\n\t\tself.table = map(lambda x: x.split(\"\\t\"), rows)\n\t\tself.table = [i for i in self.table if len(i) > 1]\n\n\tdef print_labels(self):\n\t\tprint (self.labels)\n\n\n\tdef print_table(self):\n\t\tprint (self.table)\n\n\tdef get_col_data(self, background=[]):\n\t\tdata = []\n\t\ttime = []\n\t\tif background == []:\n\t\t\tbackground = [0] * len(self.table)\n\t\tfor row in range(len(self.table)):\n\t\t\ttime.append(float(self.table[row][3]))\n\t\t\tdata.append(float(self.table[row][4]) - background[row])\n\t\treturn (time, data)\n\n\tdef plot_attribute(self, num):\n\t\timport matplotlib.pyplot as plt\n\t\tdata = []\n\t\ttime = []\n\t\tfor row in self.table:\n\t\t\ttime.append(float(row[3]))\n\t\t\tdata.append(float(row[num]))\n\t\tplt.plot(time, data)\n\t\tplt.ylabel(self.labels[num])\n\t\tplt.xlabel(self.labels[3])\n\t\tplt.show()\n","sub_path":"cycle.py","file_name":"cycle.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"355699225","text":"#!/cygdrive/c/Python310/Python.exe\n\nconfigList = \\\n (\n \"arc panel\",\n\n ('arcAddFeed', 'arc '),\n ('arcBallDist', 'arc '),\n ('arcCCW', 'arc '),\n ('arcDiam', 'arc '),\n ('arcFeed', 'arc '),\n ('arcFinish', 'arc '),\n ('arcLargeEnd', 'arc '),\n ('arcLargeStem', 'arc '),\n ('arcPasses', 'arc '),\n ('arcPause', 'arc '),\n ('arcRetract', 'arc '),\n ('arcRadius', 'arc '),\n ('arcRPM', 'arc '),\n ('arcSmallEnd', 'arc '),\n ('arcSmallStem', 'arc '),\n ('arcSPInt', 'arc '),\n ('arcSpring', 'arc '),\n ('arcToolAngle', 'arc '),\n ('arcToolRad', 'arc '),\n ('arcType', 'arc '),\n ('arcXFeed', 'arc '),\n ('arcZFeed', 'arc '),\n ('arcZStart', 'arc '),\n\n \"system config\",\n\n ('cfgCmdDis', 'config disable sending commands'),\n ('cfgCommonLimits', 'config all limit switches on one pin'),\n ('cfgLimitsEnabled', 'config limits enabled'),\n ('cfgCommonHome', 'config all switches on one pin'),\n ('cfgDbgSave', 'config save debug info'),\n ('cfgDRO', 'config dro present'),\n ('cfgDraw', 'config draw paths'),\n ('cfgEncoder', 'config encoder counts per revolution'),\n ('cfgEStop', 'config estop enable'),\n ('cfgEStopInv', 'config estop invert'),\n ('cfgExtDro', 'config external digital readout'),\n ('cfgFcy', 'config microprocessor clock frequency'),\n ('cfgFpga', 'config fpga interface present'),\n ('cfgFpgaFreq', 'config fpga frequency'),\n ('cfgFreqMult', 'config fpga frequency multiplier'),\n ('cfgHomeInPlace', 'config home in place'),\n ('cfgIntSync', 'config internal sync'),\n ('cfgInvEncDir', 'config fpga invert encoder direction'),\n ('cfgLCD', 'config enable lcd'),\n ('cfgMega', 'config control link to mega'),\n ('cfgMPG', 'config enable manual pulse generator'),\n ('cfgPrbInv', 'config invert probe signal'),\n ('cfgRemDbg', 'config print remote debug info'),\n ('cfgSpEncCap', 'config encoder on capture interrupt'),\n ('cfgSpEncoder', 'config spindle encoder'),\n ('cfgSpSync', 'config spindle using timer'),\n ('cfgSpSyncBoard', 'config spindle sync board'),\n ('cfgSpUseEncoder', 'config use spindle encoder for threading'),\n ('cfgSyncSPI', 'config sync comm through spi'),\n ('cfgTaperCycleDist', 'config taper cycle distance'),\n ('cfgTestMode', 'conifg test mode'),\n ('cfgTestRPM', 'config fpga test rpm value'),\n ('cfgTurnSync', 'config for turning synchronization'),\n ('cfgThreadSync', 'config for threading synchronization'),\n\n \"communications cxonfig\",\n\n ('commPort', 'comm port'),\n ('commRate', 'comm baud rate'),\n\n \"cutoff config\",\n\n ('cuPause', 'cutoff pause before cutting'),\n ('cuRPM', 'cutoff rpm'),\n ('cuToolWidth', 'cutoff tool width'),\n ('cuXEnd', 'cutoff x end'),\n ('cuXFeed', 'cutoff x feed'),\n ('cuXRetract', 'cutoff x retract'),\n ('cuXStart', 'cutoff x start'),\n ('cuZCutoff', 'cutoff offset to z cutoff'),\n ('cuZRetract', 'cutoff offset to z retract'),\n ('cuZStart', 'cutoff z location'),\n\n \"dro position\",\n\n ('droXPos', 'dro x position'),\n ('droZPos', 'dro z position'),\n\n \"external dro\",\n\n ('extDroPort', 'external dro port'),\n ('extDroRate', 'external dro baud Rate'),\n\n \"face config\",\n\n ('faAddFeed', 'face '),\n ('faPasses', 'face '),\n ('faPause', 'face pause before cutting'),\n ('faRPM', 'face '),\n ('faSPInt', 'face '),\n ('faSpring', 'face '),\n ('faXEnd', 'face '),\n ('faXFeed', 'face '),\n ('faXRetract', 'face '),\n ('faXStart', 'face '),\n ('faZEnd', 'face '),\n ('faZFeed', 'face '),\n ('faZRetract', 'face '),\n ('faZStart', 'face '),\n\n \"jog config\",\n\n ('jogInc', 'jog '),\n ('jogXPos', 'jog '),\n ('jogXPosDiam', 'jog '),\n ('jogZPos', 'jog '),\n\n \"jog panel config\",\n\n ('jpSurfaceSpeed', 'jogpanle fpm or rpm'),\n ('jpXDroDiam', 'jogpanel x dro diameter'),\n\n \"jog time parameters\",\n\n ('jogTimeInitial', 'jog time initial'),\n ('jogTimeInc', 'jog time increment'),\n ('jogTimeMax', 'jog time max'),\n\n \"keypad\",\n\n ('keypadPort', 'external dro port'),\n ('keypadRate', 'external dro baud Rate'),\n\n \"main panel\",\n\n ('mainPanel', 'name of main panel'),\n\n \"mega config\",\n\n ('cfgMegaVFD', 'mega vfd speed mode'),\n ('cfgMegaEncTest', 'mega encoder test'),\n ('cfgMegaEncLines', 'mega encoder lines'),\n # ('mega', 'mega'),\n\n \"spindle config\",\n\n ('spAccel', 'spindle acceleration'),\n ('spAccelTime', 'spindle acceleration time'),\n ('spCurRange', 'spindle current range'),\n ('spInvDir', 'spindle invert direction'),\n ('spJogAccelTime', 'spindle jog acceleration time'),\n ('spJogMax', 'spindle jog max speed'),\n ('spJogMin', 'spindle jog min speed'),\n ('spJTimeInc', 'spindle jog increment'),\n ('spJTimeInitial', 'spindle jog initial time '),\n ('spJTimeMax', 'spindle jog max'),\n ('spMaxRPM', 'spindle jog max rpm'),\n ('spMicroSteps', 'spindle micro steps'),\n ('spMinRPM', 'spindle minimum rpm'),\n ('spMotorSteps', 'spindle motor stpes per revolution'),\n ('spMotorTest', 'use stepper drive to test motor'),\n ('spPWMFreq', 'spindle pwm frequency'),\n ('spMegaSim', 'spindle use mega to simulate index and encoder'),\n\n ('spRangeMin1', 'spindle speed range 1 minimum'),\n ('spRangeMin2', 'spindle speed range 2 minimum'),\n ('spRangeMin3', 'spindle speed range 3 minimum'),\n ('spRangeMin4', 'spindle speed range 4 minimum'),\n ('spRangeMin5', 'spindle speed range 5 minimum'),\n ('spRangeMin6', 'spindle speed range 6 minimum'),\n\n ('spRangeMax1', 'spindle speed range 1 maximum'),\n ('spRangeMax2', 'spindle speed range 2 maximum'),\n ('spRangeMax3', 'spindle speed range 3 maximum'),\n ('spRangeMax4', 'spindle speed range 4 maximum'),\n ('spRangeMax5', 'spindle speed range 5 maximum'),\n ('spRangeMax6', 'spindle speed range 6 maximum'),\n\n ('spRanges', 'spindle number of speed ranges'),\n ('spStepDrive', 'spindle stepper drive'),\n ('spSwitch', 'spindle off on switch'),\n ('spTestEncoder', 'spindle test generate encoder test pulse'),\n ('spTestIndex', 'spindle test generate internal index pulse'),\n ('spVarSpeed', 'spindle variable speed'),\n\n \"sync communications config\",\n\n ('syncPort', 'sync comm port'),\n ('syncRate', 'sync comm baud rate'),\n\n \"threading config\",\n\n ('thAddFeed', 'thread feed to add after done'),\n ('thAlternate', 'thread alternate thread flanks'),\n ('thAngle', 'thread half angle of thread'),\n ('thFirstFeed', 'thread first feed for thread area calc'),\n ('thFirstFeedBtn', 'thread button to select first feed'),\n ('thInternal', 'thread internal threads'),\n ('thLastFeed', 'thread last feed for thread area calculation'),\n ('thLastFeedBtn', 'thread button to select last feed'),\n ('thLeftHand', 'thread left hand '),\n ('thMM', 'thread button for mm'),\n ('thPasses', 'thread number of passes'),\n ('thPause', 'thread pause between passes'),\n ('thRPM', 'thread speed for threading operation'),\n ('thRunout', 'thread runout for rh exit or lh entrance'),\n ('thSPInt', 'thread spring pass interval'),\n ('thSpring', 'thread number of spring passes at end'),\n ('thTPI', 'thread select thread in threads per inch'),\n ('thThread', 'thread field containing tpi or pitch'),\n ('thXDepth', 'thread x depth of thread'),\n ('thXRetract', 'thread x retract'),\n ('thXStart', 'thread x diameter'),\n ('thXTaper', 'thread x taper'),\n ('thZ0', 'thread z right end of thread left start'),\n ('thZ1', 'thread z right start left end'),\n ('thZRetract', 'thread z retract'),\n\n \"taper config\",\n\n ('tpAddFeed', 'tp '),\n ('tpAngle', 'tp '),\n ('tpAngleBtn', 'tp '),\n ('tpDeltaBtn', 'tp '),\n ('tpInternal', 'tp '),\n ('tpLargeDiam', 'tp '),\n ('tpPasses', 'tp '),\n ('tpPause', 'tp '),\n ('tpRPM', 'tp '),\n ('tpSPInt', 'tp '),\n ('tpSmallDiam', 'tp '),\n ('tpSpring', 'tp '),\n ('tpTaperSel', 'tp '),\n ('tpXDelta', 'tp '),\n ('tpXFeed', 'tp '),\n ('tpXFinish', 'tp '),\n ('tpXInFeed', 'tp '),\n ('tpXRetract', 'tp '),\n ('tpZDelta', 'tp '),\n ('tpZFeed', 'tp '),\n ('tpZLength', 'tp '),\n ('tpZRetract', 'tp '),\n ('tpZStart', 'tp '),\n\n \"turn config\",\n\n ('tuAddFeed', 'turn '),\n ('tuInternal', 'turn internal'),\n ('tuManual', 'turn manual mode'),\n ('tuPasses', 'turn '),\n ('tuPause', 'turn '),\n ('tuRPM', 'turn '),\n ('tuSPInt', 'turn '),\n ('tuSpring', 'turn '),\n ('tuXDiam0', 'turn '),\n ('tuXDiam1', 'turn '),\n ('tuXFeed', 'turn '),\n ('tuXRetract', 'turn '),\n ('tuZEnd', 'turn '),\n ('tuZFeed', 'turn '),\n ('tuZRetract', 'turn '),\n ('tuZStart', 'turn '),\n\n \"x axis config\",\n\n ('xAccel', 'x axis '),\n ('xBackInc', 'z axis distance to go past for taking out backlash'),\n ('xBacklash', 'x axis '),\n ('xDoneDelay', 'x axis done to read dro delay'),\n ('xDroFinalDist', 'x dro final approach dist'),\n ('xDROInch', 'x axis '),\n ('xDROPos', 'x axis use dro to go to correct position'),\n ('xHomeDir', 'x axis '),\n ('xHomeDist', 'x axis '),\n ('xHomeDistBackoff', 'x axis '),\n ('xHomeDistRev', 'x axis '),\n ('xHomeEna', 'x axis '),\n ('xHomeEnd', 'x axis '),\n ('xHomeInv', 'x axis '),\n ('xHomeLoc', 'x axis '),\n ('xHomeSpeed', 'x axis '),\n ('xHomeStart', 'x axis '),\n ('xInvDRO', 'x axis invert dro'),\n ('xInvDir', 'x axis invert stepper direction'),\n ('xInvEnc', 'x axis '),\n ('xInvMpg', 'x axis invert mpg direction'),\n ('xJogMax', 'x axis '),\n ('xJogMin', 'x axis '),\n ('xLimEna', 'x axis limits enable'),\n ('xLimNegInv', 'x axis negative limit invert'),\n ('xLimPosInv', 'x axis positive limit invert'),\n ('xMpgInc', 'x axis jog increment'),\n ('xMpgMax', 'x axis jog maximum'),\n ('xJogSpeed', 'x axis '),\n ('xMaxSpeed', 'x axis '),\n ('xMicroSteps', 'x axis '),\n ('xMinSpeed', 'x axis '),\n ('xMotorRatio', 'x axis '),\n ('xMotorSteps', 'x axis '),\n ('xRetractLoc', 'x axis '),\n ('xPitch', 'x axis '),\n ('xProbeDist', 'x axis '),\n\n \"x axis position config\",\n\n ('xSvPosition', 'x axis '),\n ('xSvHomeOffset', 'x axis '),\n ('xSvDROPosition', 'x axis '),\n ('xSvDROOffset', 'x axis '),\n\n \"z axis config\",\n\n ('zAccel', 'z axis '),\n ('zBackInc', 'z axis distance to go past for taking out backlash'),\n ('zBacklash', 'z axis '),\n ('zDoneDelay', 'z axis done to read dro delay'),\n ('zDroFinalDist', 'z dro final approach dist'),\n ('zDROPos', 'z axis use dro to go to correct position'),\n ('zDROInch', 'z axis '),\n ('zHomeDir', 'z axis '),\n ('zHomeDist', 'z axis '),\n ('zHomeDistRev', 'z axis '),\n ('zHomeDistBackoff', 'z axis '),\n ('zHomeEna', 'z axis '),\n ('zHomeEnd', 'z axis '),\n ('zHomeInv', 'z axis '),\n ('zHomeLoc', 'z axis '),\n ('zHomeSpeed', 'z axis '),\n ('zHomeStart', 'z axis '),\n ('zInvDRO', 'z axis '),\n ('zInvDir', 'z axis '),\n ('zInvEnc', 'z axis '),\n ('zInvMpg', 'z axis '),\n ('zJogMax', 'z axis '),\n ('zJogMin', 'z axis '),\n ('zMpgInc', 'z axis jog increment'),\n ('zMpgMax', 'z axis jog maximum'),\n ('zJogSpeed', 'z axis '),\n ('zLimEna', 'z axis limits enable'),\n ('zLimNegInv', 'z axis negative limit invert'),\n ('zLimPosInv', 'z axis positive limit invert'),\n ('zMaxSpeed', 'z axis '),\n ('zMicroSteps', 'z axis '),\n ('zMinSpeed', 'z axis '),\n ('zMotorRatio', 'z axis '),\n ('zMotorSteps', 'z axis '),\n ('zRetractLoc', 'z axis '),\n ('zPitch', 'z axis '),\n ('zProbeDist', 'z axis '),\n ('zProbeSpeed', 'z axis '),\n\n \"z axis position config\",\n\n ('zSvPosition', 'z axis '),\n ('zSvHomeOffset', 'z axis '),\n ('zSvDROPosition', 'z axis '),\n ('zSvDROOffset', 'z axis '),\n\n ('cfgJogDebug', 'debug jogging'),\n )\n\nstrList = \\\n (\n (\"STR_OP_NOT_ACTIVE\", \"Operation Not Active\"),\n (\"STR_OP_IN_PROGRESS\", \"Operation In Progress\"),\n (\"STR_NOT_PAUSED\", \"Not Paused\"),\n (\"STR_NOT_SENT\", \"Data Not Sent\"),\n (\"STR_NO_ADD\", \"Cannot Add\"),\n (\"STR_PASS_ERROR\", \"Passcount Incorrect\"),\n (\"STR_NOT_HOMED\", \"X Not Homed\"),\n (\"STR_FIELD_ERROR\", \"Entry Field Error\"),\n (\"STR_READALL_ERROR\", \"ReadAll Error\"),\n (\"STR_TIMEOUT_ERROR\", \"Timeout Error\"),\n (\"STR_SIGN_ERROR\", \"X End and X Start do not have same sign\"),\n (\"STR_INTERNAL_ERROR\", \"X End < X Start\"),\n (\"STR_EXTERNAL_ERROR\", \"X End > X Start\"),\n (\"STR_HOME_SUCCESS\", \"Home Success\"),\n (\"STR_HOME_FAIL\", \"Home Fail\"),\n (\"STR_PROBE_SUCCESS\", \"Probe Success\"),\n (\"STR_PROBE_FAIL\", \"Probe Fail\"),\n (\"STR_STOPPED\", \"Stopped\"),\n (\"STR_CLR\", \"\"),\n )\n\ncmdList = \\\n (\n \"z motion commands\",\n\n (\"ZMOVEABS\", \"zMoveAbs\", \"start z movement\"),\n (\"ZMOVEREL\", \"zMoveRel\", \"move z relative\"),\n (\"ZJMOV\", \"zJogMove\", \"start z jog\"),\n (\"ZJSPEED\", \"zJogSpeed\", \"start z jog at speed\"),\n (\"ZSTOP\", \"zStop\", \"stop z movement\"),\n (\"ZSETLOC\", \"\", \"\"),\n (\"ZHOMEFWD\", \"zHomeFwd\", \"z home from positive side\"),\n (\"ZHOMEREV\", \"zHomeRev\", \"z home from negative side\"),\n\n \"x motion commands\",\n\n (\"XMOVEABS\", \"xMoveAbs\", \"start x movement\"),\n (\"XMOVEREL\", \"xMoveRel\", \"move x relative\"),\n (\"XJMOV\", \"xJogMove\", \"start z jog\"),\n (\"XJSPEED\", \"xJogSpeed\", \"start x jog at speed\"),\n (\"XSTOP\", \"xStop\", \"stop x movement\"),\n (\"XSETLOC\", \"\", \"\"),\n (\"XHOMEFWD\", \"xHomeFwd\", \"x home from positive side\"),\n (\"XHOMEREV\", \"xHomeRev\", \"x home from negative side\"),\n\n \"spindle operations\",\n\n (\"SPINDLE_START\", \"spindleStart\", \"start spindle\"),\n (\"SPINDLE_STOP\", \"spindleStop\", \"stop spindle\"),\n (\"SPINDLE_UPDATE\", \"spindleUpdate\", \"update spindle speed\"),\n (\"SPINDLE_JOG\", \"spindleJog\", \"spindle jog\"),\n (\"SPINDLE_JOG_SPEED\", \"spindleJogSpeed\", \"spindle jog at speed\"),\n\n \"end operations\",\n\n (\"CMD_PAUSE\", \"pauseCmd\", \"pause current operation\"),\n (\"CMD_RESUME\", \"resumeCmd\", \"resume current operation\"),\n (\"CMD_STOP\", \"stopCmd\", \"stop current operation\"),\n (\"CMD_DONE\", \"doneCmd\", \"done current operation\"),\n (\"CMD_MEASURE\", \"measureCmd\", \"stop at end of current pass\"),\n\n \"setup operations\",\n\n (\"CMD_CLEAR\", \"clearCmd\", \"clear all tables\"),\n (\"CMD_SETUP\", \"setup\", \"setup everything\"),\n (\"CMD_SPSETUP\", \"spindleSetup\", \"setup spindle\"),\n\n (\"CMD_SYNCSETUP\", \"syncSetup\", \"setup z and x axis synchronization\"),\n\n (\"CMD_ZSETUP\", \"zSetup\", \"setup z axis\"),\n (\"CMD_ZSYNSETUP\", \"\", \"setup z axis sync\"),\n (\"CMD_ZSETLOC\", \"zSetLoc\", \"setup z location\"),\n\n (\"CMD_XSETUP\", \"xSetup\", \"setup x axis\"),\n (\"CMD_XSYNSETUP\", \"\", \"setup x axis sync\"),\n (\"CMD_XSETLOC\", \"xSetLoc\", \"setup x location\"),\n\n \"state information\",\n\n (\"READSTAT\", \"\", \"read status\"),\n (\"READISTATE\", \"\", \"read states of state machines\"),\n\n \"load processor and xilinx parameters\",\n\n (\"LOADVAL\", \"\", \"load parameters\"),\n (\"LOADMULTI\", \"\", \"load multiple parameters\"),\n (\"READVAL\", \"\", \"read parameters\"),\n (\"LOADXREG\", \"\", \"load xilinx registers\"),\n (\"READXREG\", \"\", \"read xilinx registers\"),\n\n \"move command operations\",\n\n (\"CLEARQUE\", \"clearQue\", \"clear move que\"),\n (\"QUEMOVE\", \"\", \"que move command\"),\n (\"MOVEMULTI\", \"\", \"que move command\"),\n (\"MOVEQUESTATUS\", \"\", \"read move queue status\"),\n\n \"location and debug info\",\n\n (\"READALL\", \"readAll\", \"read all status info\"),\n (\"READDBG\", \"readDbg\", \"read debug message\"),\n (\"CLRDBG\", \"clearDbg\", \"clear debug message buffer\"),\n\n \"encoder commands\",\n\n (\"ENCSTART\", \"\", \"encoder start\"),\n (\"ENCSTOP\", \"\", \"encoder stop\"),\n\n \" mega commands \",\n\n (\"SET_MEGA_VAL\", \"\", \"set mega value\"),\n (\"READ_MEGA_VAL\", \"\", \"get mega value\"),\n )\n\nsyncCmdList = \\\n (\n (\"SYNC_SETUP\", \"\", \"setup sync routine\"),\n (\"SYNC_START\", \"\", \"start sync routine\"),\n (\"SYNC_STOP\", \"\", \"stop sync routine\"),\n (\"SYNC_LOADVAL\", \"\", \"load parameters\"),\n (\"SYNC_LOADMULTI\", \"\", \"load multiple parameters\"),\n (\"SYNC_READVAL\", \"\", \"read parameters\"),\n (\"SYNC_POLL\", \"\", \"poll sync board\"),\n )\n\nmegaCmdList = \\\n (\n (\"MEGA_NONE\", \"\", \"no command\"),\n (\"MEGA_SET_RPM\", \"\", \"set pwm for rpm\"),\n (\"MEGA_GET_RPM\", \"\", \"get pwm value\"),\n (\"MEGA_POLL\", \"\", \"poll mega info\"),\n (\"MEGA_SET_VAL\", \"\", \"set mega value\"),\n (\"MEGA_READ_VAL\", \"\", \"read mega value\"),\n (\"MEGA_ENC_START\", \"\", \"start mega encoder\"),\n (\"MEGA_ENC_STOP\", \"\", \"stop mega encoder\"),\n (\"MEGA_UPDATE_RPM\", \"\", \"update rpm if active\"),\n # (\"MEGA_\", \"\", \"\"),\n )\n\nparmList = \\\n (\n \"spindle parameters\",\n\n (\"SP_STEPS\", \"spindle motor steps\", \"int16_t\"),\n (\"SP_MICRO\", \"spindle micro steps\", \"int16_t\"),\n (\"SP_MIN_RPM\", \"spindle minimum rpm\", \"float\"),\n (\"SP_MAX_RPM\", \"spindle maximum rpm\", \"float\"),\n (\"SP_RPM\", \"spindle rpm\", \"float\"), #\n (\"SP_ACCEL_TIME\", \"spindle accel time\", \"float\"),\n (\"SP_ACCEL\", \"spindle accel rpm/sec^2\", \"float\"),\n (\"SP_JOG_MIN_RPM\", \"spindle jog minimum rpm\", \"float\"),\n (\"SP_JOG_MAX_RPM\", \"spindle jog maximum rpm\", \"float\"),\n (\"SP_JOG_RPM\", \"spindle jog rpm\", \"float\"),\n (\"SP_JOG_ACCEL_TIME\", \"spindle jog accel time\", \"float\"),\n (\"SP_JOG_TIME_INITIAL\", \"spindle jog time initl\", \"float\"),\n (\"SP_JOG_TIME_INC\", \"spindle jog time increment\", \"float\"),\n (\"SP_JOG_TIME_MAX\", \"spindle jog timemax\", \"float\"),\n (\"SP_JOG_DIR\", \"spindle direction\", \"char\"),\n (\"SP_DIR_FLAG\", \"spindle invert direction\", \"char\"),\n (\"SP_TEST_INDEX\", \"generate test index pulse\", \"char\"),\n (\"SP_TEST_ENCODER\", \"generate enc test pulse\", \"char\"),\n\n \"z axis parameters\",\n\n (\"Z_PITCH\", \"z axis leadscrew pitch\", \"float\"),\n (\"Z_RATIO\", \"z axis ratio\", \"float\"),\n (\"Z_MICRO\", \"z axis micro steps\", \"int16_t\"),\n (\"Z_MOTOR\", \"z axis motor steps\", \"int16_t\"),\n (\"Z_ACCEL_TIME\", \"z axis acceleration\", \"float\"),\n (\"Z_ACCEL\", \"z accel rpm/sec^2\", \"float\"),\n (\"Z_BACKLASH\", \"z axis backlash\", \"float\"),\n (\"Z_STEP_FACTOR\", \"z steps inch factored\", \"int\"),\n (\"Z_DIR_FLAG\", \"z invert direction\", \"char\"),\n (\"Z_MPG_FLAG\", \"z invert mpg\", \"char\"),\n\n \"x axis parameters\",\n\n (\"X_PITCH\", \"x axis leadscrew pitch\", \"float\"),\n (\"X_RATIO\", \"x axis ratio\", \"float\"),\n (\"X_MICRO\", \"x axis micro steps\", \"int16_t\"),\n (\"X_MOTOR\", \"x axis motor steps\", \"int16_t\"),\n (\"X_ACCEL_TIME\", \"x axis acceleration\", \"float\"),\n (\"X_ACCEL\", \"x accel rpm/sec^2\", \"float\"),\n (\"X_BACKLASH\", \"x axis backlash\", \"float\"),\n (\"X_STEP_FACTOR\", \"x steps inch factored\", \"int\"),\n (\"X_DIR_FLAG\", \"x invert direction\", \"char\"),\n (\"X_MPG_FLAG\", \"x invert mpg\", \"char\"),\n (\"X_DIAMETER\", \"x diameter\", \"int\"),\n\n \"z move parameters\",\n\n (\"Z_MOVE_MIN\", \"z move min speed\", \"float\"),\n (\"Z_MOVE_MAX\", \"z move max speed\", \"float\"),\n\n \"z jog parameters\",\n\n (\"Z_JOG_MIN\", \"z jog min speed\", \"float\"),\n (\"Z_JOG_MAX\", \"z jog max speed\", \"float\"),\n (\"Z_JOG_SPEED\", \"z jog speed\", \"float\"),\n\n \"x move parameters\",\n\n (\"X_MOVE_MIN\", \"x move min speed\", \"float\"),\n (\"X_MOVE_MAX\", \"x move max speed\", \"float\"),\n\n \"x jog parameters\",\n\n (\"X_JOG_MIN\", \"x jog min speed\", \"float\"),\n (\"X_JOG_MAX\", \"x jog max speed\", \"float\"),\n (\"X_JOG_SPEED\", \"x jog speed\", \"float\"),\n\n \"pass information\",\n\n (\"TOTAL_PASSES\", \"total passes\", \"int16_t\"),\n (\"CURRENT_PASS\", \"current passes\", \"int16_t\"),\n (\"MV_STATUS\", \"movement status\", \"int16_t\"),\n\n \"z axis move values\",\n\n (\"Z_MOVE_DIST\", \"z move distance\", \"float\"),\n (\"Z_MOVE_POS\", \"z move position\", \"float\"),\n (\"Z_JOG_DIR\", \"x jog direction\", \"int\"),\n (\"Z_SET_LOC\", \"z location to set\", \"float\"),\n (\"Z_LOC\", \"z dro location\", \"int\"),\n (\"Z_FLAG\", \"z move flag\", \"int\"),\n (\"Z_ABS_LOC\", \"z absolute location\", \"int\"),\n (\"Z_MPG_INC\", \"z man pulse gen incr\", \"int\"),\n (\"Z_MPG_MAX\", \"z man pulse max distance\", \"int\"),\n\n \"x axis move values\",\n\n (\"X_MOVE_DIST\", \"x move distance\", \"float\"),\n (\"X_MOVE_POS\", \"x move position\", \"float\"),\n (\"X_JOG_DIR\", \"x jog direction\", \"int\"),\n (\"X_SET_LOC\", \"x location to set\", \"float\"),\n (\"X_LOC\", \"x dro location\", \"int\"),\n (\"X_FLAG\", \"x move flag\", \"int\"),\n (\"X_ABS_LOC\", \"x absolute location\", \"int\"),\n (\"X_MPG_INC\", \"X man pulse gen incr\", \"int\"),\n (\"X_MPG_MAX\", \"x man pulse max distance\", \"int\"),\n\n \"common jog parameters\",\n\n (\"JOG_TIME_INITIAL\", \"jog time initial\", \"float\"),\n (\"JOG_TIME_INC\", \"jog time increment\", \"float\"),\n (\"JOG_TIME_MAX\", \"jog time max\", \"float\"),\n\n \"taper parameters\",\n\n (\"TAPER_CYCLE_DIST\", \"taperCycleDist\", \"float\"),\n\n \"index pulse variables\",\n\n (\"INDEX_PRE_SCALER\", \"index pre scaler\", \"int\"),\n (\"LAST_INDEX_PERIOD\", \"last index period\", \"unsigned int\"),\n (\"INDEX_PERIOD\", \"index period\", \"unsigned int\"),\n (\"REV_COUNTER\", \"revolution counter\", \"unsigned int\"),\n\n \"z home offset\",\n\n (\"Z_HOME_OFFSET\", \"z home offset\", \"int\"),\n\n \"x home offset\",\n\n (\"X_HOME_OFFSET\", \"x home offset\", \"int\"),\n\n \"z home parameters\",\n\n (\"Z_HOME_SPEED\", \"z final homing speed\", \"float\"),\n (\"Z_HOME_DIST\", \"z max homing distance\", \"float\"),\n (\"Z_HOME_DIST_REV\", \"z max rev homing distance\", \"float\"),\n (\"Z_HOME_DIST_BACKOFF\", \"z home backoff dist\", \"float\"),\n (\"Z_HOME_DIR\", \"z homing direction\", \"int\"),\n\n \"x home parameters\",\n\n (\"X_HOME_SPEED\", \"x final homing speed\", \"float\"),\n (\"X_HOME_DIST\", \"x max homing distance\", \"float\"),\n (\"X_HOME_DIST_REV\", \"x max rev homing distance\", \"float\"),\n (\"X_HOME_DIST_BACKOFF\", \"x home backoff dist\", \"float\"),\n (\"X_HOME_DIR\", \"x homing direction\", \"int\"),\n\n \"x home test parameters\",\n\n (\"X_HOME_LOC\", \"x home test location\", \"int\"),\n (\"X_HOME_START\", \"x start of home signal\", \"int\"),\n (\"X_HOME_END\", \"x end of home signal\", \"int\"),\n\n \"z dro\",\n\n (\"Z_DRO_LOC\", \"z dro location\", \"int\"),\n (\"Z_DRO_OFFSET\", \"z dro to zero\", \"int\"),\n (\"Z_DRO_COUNT_INCH\", \"z dro scale\", \"int\"),\n (\"Z_DRO_FACTOR\", \"x dro counts inch factored\", \"int\"),\n (\"Z_DRO_INVERT\", \"z dro invert\", \"int\"),\n (\"Z_USE_DRO\", \"z use dro for position\", \"char\"),\n (\"Z_DONE_DELAY\", \"z done to read dro delay\", \"int\"),\n (\"Z_DRO_FINAL_DIST\", \"z final approach distance\", \"int\"),\n\n \"x dro\",\n\n (\"X_DRO_LOC\", \"x dro location\", \"int\"),\n (\"X_DRO_OFFSET\", \"x dro to zero\", \"int\"),\n (\"X_DRO_COUNT_INCH\", \"x dro scale\", \"int\"),\n (\"X_DRO_FACTOR\", \"x dro counts inch factored\", \"int\"),\n (\"X_DRO_INVERT\", \"x dro invert\", \"int\"),\n (\"X_USE_DRO\", \"x use dro for position\", \"char\"),\n (\"X_DONE_DELAY\", \"x done to read dro delay\", \"int\"),\n (\"X_DRO_FINAL_DIST\", \"x final approach distance\", \"int\"),\n\n \"x home or probe status\",\n\n # (\"X_HOME_DONE\", \"x home done\", \"int\"),\n (\"X_HOME_STATUS\", \"x home status\", \"int\"),\n\n \"Z home or probe status\",\n\n # (\"Z_HOME_DONE\", \"z home done\", \"int\"),\n (\"Z_HOME_STATUS\", \"z home status\", \"int\"),\n\n \"probe configuration\",\n\n (\"PROBE_SPEED\", \"probe speed\", \"float\"),\n (\"PROBE_DIST\", \"probe test distance\", \"int\"),\n (\"PROBE_INV\", \"invert polarity of probe\", \"int\"),\n\n \"configuration\",\n\n (\"STEPPER_DRIVE\", \"stepper driven spindle\", \"char\"),\n (\"MOTOR_TEST\", \"use stepper to test motor\", \"char\"),\n (\"SPINDLE_ENCODER\", \"motor with spindle enc\", \"char\"),\n (\"SPINDLE_SYNC_BOARD\", \"spindle sync board\", \"char\"),\n (\"SPINDLE_INTERNAL_SYNC\", \"spindle internal sync\", \"char\"),\n (\"TURN_SYNC\", \"sync type for turning\", \"char\"),\n (\"THREAD_SYNC\", \"sync type for threading\", \"char\"),\n # (\"SPINDLE_SYNC\", \"spindle sync direct\", \"char\"),\n # (\"USE_ENCODER\", \"config for use encoder interrupt directly\", \"char\"),\n # (\"ENCODER_DIRECT\", \"use encoder interrupt directly\", \"char\"),\n (\"CAP_TMR_ENABLE\", \"enable capture timer\", \"char\"),\n (\"CFG_FPGA\", \"using fpga\", \"char\"),\n (\"CFG_MEGA\", \"control link to mega\", \"char\"),\n (\"CFG_MPG\", \"manual pulse generator\", \"char\"),\n (\"CFG_DRO\", \"digital readout\", \"char\"),\n (\"CFG_LCD\", \"lcd display\", \"char\"),\n (\"CFG_FCY\", \"system clock speed\", \"unsigned int\"),\n (\"CFG_SWITCH\", \"spindle off on switch\", \"int\"),\n (\"CFG_VAR_SPEED\", \"spindle variable speed\", \"int\"),\n\n \"setup\",\n\n (\"SETUP_DONE\", \"setup done\", \"char\"),\n\n \"encoder counts per revolution\",\n\n (\"ENC_PER_REV\", \"spindle enc counts per rev\", \"uint16_t\"),\n\n \"test encoder setup variables\",\n\n (\"ENC_ENABLE\", \"encoder enable flag\", \"char\"),\n (\"ENC_PRE_SCALER\", \"encoder prescaler\", \"uint16_t\"),\n (\"ENC_TIMER\", \"encoder timer counts\", \"uint16_t\"),\n (\"ENC_RUN_COUNT\", \"encoder run count\", \"int\"),\n\n \"test encoder status variables\",\n\n (\"ENC_RUN\", \"encoder running flag\", \"char\"),\n (\"ENC_COUNTER\", \"encoder count in rev\", \"int16_t\"),\n (\"ENC_REV_COUNTER\", \"encoder revolution counter\", \"int32_t\"),\n\n \"measured spindle speed\",\n\n (\"RPM\", \"current measured rpm\", \"int16_t\"),\n\n \"fpga frequency variables\",\n\n (\"FPGA_FREQUENCY\", \"fpga clock frequency\", \"int32_t\"),\n (\"FREQ_MULT\", \"frequency multiplier\", \"int16_t\"),\n\n \"xilinx configuration register\",\n\n (\"X_CFG_REG\", \"xilinx cfg register\", \"int16_t\"),\n\n \"z sync parameters\",\n\n (\"L_SYNC_CYCLE\", \"sync cycle length\", \"uint16_t\"),\n (\"L_SYNC_OUTPUT\", \"sync outputs per cycle\", \"uint16_t\"),\n (\"L_SYNC_IN_PRESCALER\", \"input sync prescaler\", \"uint16_t\"),\n (\"L_SYNC_OUT_PRESCALER\", \"output sync prescaler\", \"uint16_t\"),\n\n \"x sync parameters\",\n\n (\"L_X_SYNC_CYCLE\", \"sync cycle length\", \"uint16_t\"),\n (\"L_X_SYNC_OUTPUT\", \"sync outputs per cycle\", \"uint16_t\"),\n (\"L_X_SYNC_IN_PRESCALER\", \"input sync prescaler\", \"uint16_t\"),\n (\"L_X_SYNC_OUT_PRESCALER\", \"output sync prescaler\", \"uint16_t\"),\n\n \"threading variables\",\n\n (\"TH_Z_START\", \"threading z start\", \"int32_t\"),\n (\"TH_X_START\", \"threading x start\", \"int32_t\"),\n (\"TAN_THREAD_ANGLE\", \"tan of threading angle\", \"float\"),\n (\"X_FEED\", \"x feed\", \"int32_t\"),\n (\"RUNOUT_DISTANCE\", \"runout distance\", \"float\"),\n (\"RUNOUT_DEPTH\", \"runout depth\", \"float\"),\n\n \"jog debug\",\n\n (\"JOG_DEBUG\", \"jog interrupt debug\", \"char\"),\n\n \"motor and speed control\",\n\n (\"PWM_FREQ\", \"spindle speed pwm frequency\", \"unsigned int\"),\n (\"MIN_SPEED\", \"min speed for current range\", \"int16_t\"),\n (\"MAX_SPEED\", \"max speed for current range\", \"int16_t\"),\n\n \"current operation\",\n\n (\"CURRENT_OP\", \"current operation\", \"char\"),\n\n \"global limits and home\",\n\n (\"LIMIT_OVERRIDE\", \"override limit switches\", \"char\"),\n (\"COMMON_LIMITS\", \"all limit switches one pin\", \"char\"),\n (\"LIMITS_ENABLED\", \"limits enabled\", \"char\"),\n (\"COMMON_HOME\", \"all home switches one pin\", \"char\"),\n\n \"z limits and home\",\n\n (\"Z_LIM_ENA\", \"z limit enable\", \"char\"),\n (\"Z_LIM_NEG_INV\", \"z negative limit invert\", \"char\"),\n (\"Z_LIM_POS_INV\", \"z Positive limit Invert\", \"char\"),\n\n (\"Z_HOME_ENA\", \"z home enable\", \"char\"),\n (\"Z_HOME_INV\", \"z home invert\", \"char\"),\n\n \"x limits and home\",\n\n (\"X_LIM_ENA\", \"x limit enable\", \"char\"),\n (\"X_LIM_NEG_INV\", \"x negative limit invert\", \"char\"),\n (\"X_LIM_POS_INV\", \"x Positive limit Invert\", \"char\"),\n\n (\"X_HOME_ENA\", \"x home enable\", \"char\"),\n (\"X_HOME_INV\", \"x home invert\", \"char\"),\n\n \"e stop\",\n\n (\"E_STOP_ENA\", \"enable estop\", \"char\"),\n (\"E_STOP_INV\", \"invert estop signal\", \"char\"),\n\n \"command pause\",\n\n (\"CMD_PAUSED\", \"move commands paused\", \"char\"),\n\n \"arc parameters\",\n\n (\"ARC_RADIUS\", \"arc radius\", \"float\"),\n (\"ARC_X_CENTER\", \"arc x center\", \"int\"),\n (\"ARC_Z_CENTER\", \"arc z center\", \"int\"),\n (\"ARC_X_START\", \"arc x start\", \"int\"),\n (\"ARC_Z_START\", \"arc z start\", \"int\"),\n (\"ARC_X_END\", \"arc x center\", \"int\"),\n (\"ARC_Z_END\", \"arc z center\", \"int\"),\n\n ('MEGA_VFD', 'mega vfd speed mode', \"char\"),\n ('MEGA_SIM', 'mega encoder lines', \"char\"),\n\n ('USB_ENA', 'enable usb', \"char\"),\n\n # (\"\", \"\", \"\"),\n # (\"\", \"\", \"\"),\n # (\"\", \"\", \"\"),\n\n (\"MAX_PARM\", \"maximum parameter\", \"int16_t\")\n )\n\nsyncParmList = \\\n (\n (\"SYNC_CYCLE\", \"sync cycle length\", \"uint16_t\"),\n (\"SYNC_OUTPUT\", \"sync outputs per cycle\", \"uint16_t\"),\n (\"SYNC_PRESCALER\", \"sync prescaler\", \"uint16_t\"),\n (\"SYNC_ENCODER\", \"sync encoder pulses\", \"uint16_t\"),\n (\"SYNC_MAX_PARM\", \"sync maximum parameter\", \"int16_t\"),\n )\n\nmegaParmList = \\\n (\n (\"M_PARM_RPM\", \"rpm value\", \"int\"),\n (\"M_PARM_VFD_ENA\", \"\", \"char\"),\n (\"M_PARM_PWM_CFG\", \"\", \"char\"),\n (\"M_PARM_ENC_TEST\", \"\", \"char\"),\n (\"M_PARM_ENC_LINES\", \"\", \"int\"),\n (\"M_PARM_MAX_PARM\", \"mega maximum parameter\", \"char\"),\n # (\"M_PARM_\", \"\", \"char\"),\n )\n\nregList = \\\n (\n \"common move command bits\",\n\n (\"CMD_MSK\", \"(7 << 0)\", \"move mask\"),\n (\"CMD_MOV\", \"(1 << 0)\", \"move a set distance\"),\n (\"CMD_JOG\", \"(2 << 0)\", \"move while cmd are present\"),\n (\"CMD_SYN\", \"(3 << 0)\", \"move dist synchronized to rotation\"),\n (\"CMD_MAX\", \"(4 << 0)\", \"rapid move\"),\n (\"CMD_SPEED\", \"(5 << 0)\", \"jog at speed\"),\n (\"JOGSLOW\", \"(6 << 0)\", \"slow jog for home or probe\"),\n\n (\"SYN_START\", \"(1 << 4)\", \"start on sync pulse\"),\n (\"SYN_LEFT\", \"(1 << 5)\", \"start sync left\"),\n (\"SYN_TAPER\", \"(1 << 6)\", \"taper on other axis\"),\n (\"FIND_HOME\", \"(1 << 7)\", \"find home\"),\n (\"CLEAR_HOME\", \"(1 << 8)\", \"move off of home\"),\n\n (\"FIND_PROBE\", \"(1 << 9)\", \"find probe\"),\n (\"CLEAR_PROBE\", \"(1 << 10)\", \"move off of probe\"),\n (\"DRO_POS\", \"(1 << 11)\", \"use dro for moving\"),\n (\"DRO_UPD\", \"(1 << 12)\", \"update internal position from dro\"),\n\n \"common definitions\",\n\n (\"DIR_POS\", \"1\", \"positive direction\"),\n (\"DIR_NEG\", \"-1\", \"negative direction\"),\n\n \"z move command bits\",\n\n (\"Z_SYN_START\", \"(1 << 4)\", \"start on sync pulse\"),\n (\"Z_SYN_LEFT\", \"(1 << 5)\", \"start sync left\"),\n (\"X_SYN_TAPER\", \"(1 << 6)\", \"taper on x\"),\n\n \"z direction\",\n\n (\"ZPOS\", \"1\", \"z in positive direction\"),\n (\"ZNEG\", \"-1\", \"z in negative direction\"),\n\n \"x move command bits\",\n\n (\"X_SYN_START\", \"(1 << 4)\", \"start on sync pulse\"),\n (\"Z_SYN_TAPER\", \"(1 << 6)\", \"taper on z\"),\n\n \"x direction\",\n\n (\"XPOS\", \"1\", \"x in positive direction\"),\n (\"XNEG\", \"-1\", \"x in negative direction\"),\n\n \"feed types\",\n\n (\"FEED_PITCH\", \"0\", \"feed inch per rev\"),\n (\"FEED_TPI\", \"1\", \"feed threads per inch\"),\n (\"FEED_METRIC\", \"2\", \"feed mm per rev\"),\n\n \"home flag\",\n\n (\"HOME_SET\", \"(1 << 0)\", \"\"),\n (\"HOME_CLR\", \"(1 << 1)\", \"\"),\n (\"PROBE_SET\", \"(1 << 2)\", \"\"),\n (\"PROBE_CLR\", \"(1 << 3)\", \"\"),\n\n \"home direction\",\n\n (\"HOME_FWD\", \"0\", \"\"),\n (\"HOME_REV\", \"1\", \"\"),\n\n \"home status\",\n\n (\"HOME_ACTIVE\", \"0\", \"\"),\n (\"HOME_SUCCESS\", \"1\", \"\"),\n (\"HOME_FAIL\", \"2\", \"\"),\n\n \"probe status\",\n\n (\"PROBE_SUCCESS\", \"1\", \"\"),\n (\"PROBE_FAIL\", \"2\", \"\"),\n\n \"movement status\",\n\n (\"MV_PAUSE\", \"(1 << 0)\", \"movement paused\"),\n (\"MV_READ_X\", \"(1 << 1)\", \"pause x may change\"),\n (\"MV_READ_Z\", \"(1 << 2)\", \"pause z may change\"),\n (\"MV_ACTIVE\", \"(1 << 3)\", \"movement active\"),\n (\"MV_DONE\", \"(1 << 4)\", \"movement active\"),\n (\"MV_XLIMIT\", \"(1 << 5)\", \"at limit switch\"),\n (\"MV_ZLIMIT\", \"(1 << 6)\", \"at limit switch\"),\n (\"MV_XHOME_ACTIVE\", \"(1 << 7)\", \"x home active\"),\n (\"MV_XHOME\", \"(1 << 8)\", \"x home success\"),\n (\"MV_ZHOME_ACTIVE\", \"(1 << 9)\", \"z home active\"),\n (\"MV_ZHOME\", \"(1 << 10)\", \"z home success\"),\n (\"MV_MEASURE\", \"(1 << 11)\", \"pause for measurement\"),\n (\"MV_ESTOP\", \"(1 << 12)\", \"estop\"),\n\n \"pause flags\",\n\n (\"PAUSE_ENA_Z_JOG\", \"(1 << 0)\", \"enable z job during pause\"),\n (\"PAUSE_ENA_X_JOG\", \"(1 << 1)\", \"enable x jog during pause\"),\n (\"DISABLE_JOG\", \"(1 << 2)\", \"jogging disabled\"),\n (\"PAUSE_READ_X\", \"(1 << 3)\", \"read x after pause\"),\n (\"PAUSE_READ_Z\", \"(1 << 4)\", \"read z after pause\"),\n\n \"thread flags\",\n\n (\"TH_THREAD\", \"(1 << 0)\", \"threading\"),\n (\"TH_INTERNAL\", \"(1 << 1)\", \"internal threads\"),\n (\"TH_LEFT\", \"(1 << 2)\", \"left hand thread\"),\n (\"TH_RUNOUT\", \"(1 << 3)\", \"runout with thread\"),\n\n \"parameters for op_done\",\n\n (\"PARM_START\", \"0\", \"start of operation\"),\n (\"PARM_DONE\", \"1\", \"done operation\"),\n\n \"isr active flags\",\n\n (\"ARC_SHIFT\", (6), \"shift for arc syn\"),\n\n (\"SYNC_ACTIVE_EXT\", \"(1 << 0)\", \"active for sync board\"),\n (\"SYNC_ACTIVE_TMR\", \"(1 << 1)\", \"active for internal timer\"),\n (\"SYNC_ACTIVE_ENC\", \"(1 << 2)\", \"active for encoder\"),\n (\"SYNC_ACTIVE_STEP\", \"(1 << 3)\", \"active for stepper\"),\n (\"SYNC_ACTIVE_TAPER\", \"(1 << 4)\", \"active for taper\"),\n (\"SYNC_ACTIVE_THREAD\", \"(1 << 5)\", \"active for threading\"),\n (\"ARC_ACTIVE_EXT\", \"(SYNC_ACTIVE_EXT << ARC_SHIFT)\", \"arc sync board\"),\n (\"ARC_ACTIVE_TMR\", \"(SYNC_ACTIVE_TMR << ARC_SHIFT)\", \"arc int tmr\"),\n (\"ARC_ACTIVE_ENC\", \"(SYNC_ACTIVE_ENC << ARC_SHIFT)\", \"arc encoder\"),\n (\"ARC_ACTIVE_STEP\", \"(SYNC_ACTIVE_STEP << ARC_SHIFT)\", \"arc stepper\"),\n\n \"encoder direct flags\",\n\n (\"Z_ENCODER_DIRECT\", \"(1 << 0)\", \"z sync directly from encoder\"),\n (\"X_ENCODER_DIRECT\", \"(1 << 1)\", \"x sync directly from encoder\"),\n\n \"point by point movement commands\",\n\n (\"PCMD_INCX_HLDZ_S1\", \"(0 << 0)\", \"step x hold z then step 1\"),\n (\"PCMD_INCX_HLDZ_SN\", \"(1 << 0)\", \"step x hold z 1 then step z\"),\n (\"PCMD_HLDX_S1_INCZ\", \"(2 << 0)\", \"step x hold z then step 1\"),\n (\"PCMD_HLDX_SN_INCZ\", \"(3 << 0)\", \"hold x 1 then step x increment z\"),\n (\"PCMD_EXTEND\", \"(4 << 0)\", \"extend command\"),\n (\"PCMD_SPARE_0\", \"(5 << 0)\", \"spare 0\"),\n (\"PCMD_SPARE_1\", \"(5 << 0)\", \"spare 1\"),\n (\"PCMD_SET_DIR\", \"(7 << 0)\", \"set direction\"),\n\n (\"PCMD_X_NEG\", \"(1 << 0)\", \"mov x negative\"),\n (\"PCMD_Z_NEG\", \"(1 << 1)\", \"mov z negative\"),\n (\"PCMD_DIR_FLAG\", \"(1 << 2)\", \"direction flag\"),\n\n (\"PCMD_CMD_MASK\", \"(7 << 0)\", \"command mask\"),\n\n (\"PCMD_RPT_SHIFT\", \"(3)\", \"repeat mask\"),\n (\"PCMD_RPT_SHORT\", \"(32)\", \"repeat short\"),\n (\"PCMD_RPT_MASK\", \"(0x1f << PCMD_RPT_SHIFT)\", \"repeat shift\"),\n\n (\"PEXT_OFFSET\", \"(8)\", \"\"),\n (\"PEXT_INCX\", \"(0 << 0)\", \"step x\"),\n (\"PEXT_INCZ\", \"(1 << 0)\", \"step z\"),\n (\"PEXT_INCX_INCZ\", \"(2 << 0)\", \"step x and z\"),\n (\"PEXT_INCX2_INCZ\", \"(3 << 0)\", \"step x 2 step z\"),\n\n # (\"\", \"()\", \"\"),\n # (\"\", \"\", \"\"),\n )\n\n# (\"\", 0, 0, \"\"),\nfpgaEncList = \\\n (\n (\"F_Noop\", 0, 1, 0, \"register 0\"),\n\n (\"F_Ld_Run_Ctl\", None, 1, 1, \"load run control register\"),\n (\"F_Ld_Dbg_Ctl\", None, 1, 1, \"load debug control register\"),\n\n (\"F_Ld_Enc_Cycle\", None, 1, 2, \"load encoder cycle\"),\n (\"F_Ld_Int_Cycle\", None, 1, 2, \"load internal cycle\"),\n\n (\"F_Rd_Cmp_Cyc_Clks\", None, 1, 4, \"read cmp cycle clocks\"),\n\n (\"F_Ld_Dbg_Freq\", None, 1, 2, \"load debug frequency\"),\n (\"F_Ld_Dbg_Count\", None, 1, 2, \"load debug clocks\"),\n )\n\nfpgaLatheList = \\\n (\n \"phase control\",\n\n (\"phaseCtl\",),\n (\"F_Ld_Phase_Len\", 0, 1, 2, \"phase length\"),\n (\"F_Rd_Phase_Syn\", None, 1, 4, \"read phase at sync pulse\"),\n (\"F_Phase_Max\", None, None, 0, \"number of phase registers\"),\n\n \"controller\",\n\n (\"controller\",),\n (\"F_Ld_Ctrl_Data\", 0, 1, 0, \"load controller data\"),\n (\"F_Ctrl_Cmd\", None, 1, 1, \"controller command\"),\n (\"F_Ld_Seq\", None, 1, 1, \"load sequence\"),\n (\"F_Rd_Seq\", None, 1, 4, \"read sequence\"),\n (\"F_Rd_Ctr\", None, 1, 4, \"read counter\"),\n (\"F_Ctrl_Max\", None, None, 0, \"number of controller registers\"),\n\n \"reader\",\n\n (\"reader\",),\n (\"F_Ld_Read_Data\", 0, 1, 0, \"load reader data\"),\n (\"F_Read\", None, 1, 0, \"read data\"),\n (\"F_Read_Max\", None, None, 0, \"number of reader registers\"),\n\n \"PWM\",\n\n (\"pwmCtl\",),\n (\"F_Ld_PWM_Max\", 0, 1, 4, \"pwm counter maximum\"),\n (\"F_Ld_PWM_Trig\", 0, 1, 4, \"pwm trigger\"),\n (\"F_PWM_Max\", None, None, 0, \"number of pwm registers\"),\n\n \"encoder\",\n\n (\"encoder\",),\n (\"F_Ld_Enc_Cycle\", 0, 1, 2, \"load encoder cycle\"),\n (\"F_Ld_Int_Cycle\", None, 1, 2, \"load internal cycle\"),\n (\"F_Rd_Cmp_Cyc_Clks\", None, 1, 4, \"read cmp cycle clocks\"),\n (\"F_Enc_Max\", None, None, 0, \"number of encoder registers\"),\n\n \"debug frequency\",\n\n (\"dbgFreq\",),\n (\"F_Ld_Dbg_Freq\", 0, 1, 2, \"debug frequency\"),\n (\"F_Ld_Dbg_Count\", None, 1, 4, \"debug count\"),\n (\"F_Dbg_Freq_Max\", None, None, 0, \"number of debug frequency regs\"),\n\n \"sync accel\",\n\n (\"syncAccel\",),\n (\"F_Ld_D\", 0, 1, 4, \"axis d\"),\n (\"F_Ld_Incr1\", None, 1, 4, \"axis incr1\"),\n (\"F_Ld_Incr2\", None, 1, 4, \"axis incr2\"),\n (\"F_Ld_Accel_Val\", None, 1, 4, \"axis accel value\"),\n (\"F_Ld_Accel_Count\", None, 1, 4, \"axis accel count\"),\n\n (\"F_Rd_XPos\", None, 1, 4, \"axis x pos\"),\n (\"F_Rd_YPos\", None, 1, 4, \"axis y pos\"),\n (\"F_Rd_Sum\", None, 1, 4, \"axis sum\"),\n (\"F_Rd_Accel_Sum\", None, 1, 4, \"axis accel sum\"),\n (\"F_Rd_Accel_Ctr\", None, 1, 4, \"axis accel counter\"),\n\n (\"F_Ld_A_Dist\", None, 1, 4, \"axis distance\"),\n (\"F_Ld_Max_Dist\", None, 1, 4, \"jog maximum distance\"),\n (\"F_Ld_Backlash\", None, 1, 4, \"jog backlash\"),\n\n (\"F_Rd_A_Dist\", None, 1, 4, \"read axis distance\"),\n (\"F_Rd_A_Acl_Steps\", None, 1, 4, \"read accel steps\"),\n\n (\"F_Ld_X_Loc\", None, 1, 4, \"axis location\"),\n (\"F_Rd_X_Loc\", None, 1, 4, \"read axis location\"),\n\n (\"F_Ld_Mpg_Delta\", None, 1, 4, \"Mpg delta values\"),\n (\"F_Ld_Mpg_Dist\", None, 1, 4, \"Mpg dist values\"),\n (\"F_Ld_Mpg_Div\", None, 1, 4, \"Mpg div values\"),\n \n (\"F_Ld_Dro\", None, 1, 4, \"axis dro\"),\n (\"F_Ld_Dro_End\", None, 1, 4, \"axis dro end\"),\n (\"F_Ld_Dro_Limit\", None, 1, 4, \"axis dro decel limit\"),\n (\"F_Rd_Dro\", None, 1, 4, \"read axis dro\"),\n\n (\"F_Sync_Max\", None, None, 0, \"number of sync registers\"),\n\n # \"distance registers\",\n\n # (\"distCtr\",),\n # (\"F_Ld_Dist\", 0, 1, 4, \"axis distance\"),\n # (\"F_Rd_Dist\", None, 1, 4, \"read axis distance\"),\n # (\"F_Rd_Acl_Steps\", None, 1, 4, \"read accel steps\"),\n # (\"F_Dist_Max\", None, None, 0, \"number of distance registers\"),\n\n # \"location registers\",\n\n # (\"locCtr\",),\n # (\"F_Ld_Loc\", 0, 1, 4, \"axis location\"),\n # (\"F_Rd_Loc\", None, 1, 4, \"read axis location\"),\n # (\"F_Loc_Max\", None, None, 0, \"number of location registers\"),\n\n # \"dro registers\",\n\n # (\"dro\",),\n # (\"F_Ld_Dro\", 0, 1, 4, \"axis dro\"),\n # (\"F_Ld_Dro_End\", None, 1, 4, \"axis dro end\"),\n # (\"F_Ld_Dro_Limit\", None, 1, 4, \"axis dro deceleration limit\"),\n # (\"F_Rd_Dro\", None, 1, 4, \"read axis dro\"),\n # (\"F_Dro_Max\", None, None, 0, \"number of dro registers\"),\n\n \"jog registers\",\n\n (\"jog\",),\n (\"F_Ld_Jog_Ctl\", 0, 1, 4, \"jog control\"),\n (\"F_Ld_Jog_Inc\", None, 1, 4, \"jog increment\"),\n (\"F_Ld_Jog_Back\", None, 1, 4, \"jog backlash increment\"),\n (\"F_Jog_Max\", None, None, 0, \"number of jog registers\"),\n\n \"axis\",\n\n (\"axisCtl\",),\n (\"F_Rd_Axis_Status\", 0, 1, 1, \"read axis status\"),\n (\"F_Ld_Axis_Ctl\", None, 1, 2, \"set axis control reg\"),\n (\"F_Rd_Axis_Ctl\", None, 1, 2, \"read axis control reg\"),\n (\"F_Ld_Freq\", None, 1, 4, \"frequency\"),\n (\"F_Sync_Base\", None, \"syncAccel\", None, \"sync registers\"),\n # (\"F_Dist_Base\", None, \"distCtr\", None, \"distance registers\"),\n # (\"F_Loc_Base\", None, \"locCtr\", None, \"location registers\"),\n # (\"F_Dro_Base\", None, \"dro\", None, \"dro registers\"),\n # (\"F_Jog_Base\", None, \"jog\", None, \"jog registers\"),\n (\"F_Axis_Max\", None, None, 0, \"num of axis regs\"),\n\n \"spindle\",\n\n (\"spindle\",),\n (\"F_Ld_Sp_Ctl\", 0, 1, 1, \"spindle control reg\"),\n (\"F_Ld_Sp_Freq\", None, 1, 4, \"freq for step spindle\"),\n (\"F_Sp_Jog_Base\", None, \"jog\", None, \"spindle jog\"),\n (\"F_Sp_Sync_Base\", None, \"syncAccel\", None, \"spindle sync\"),\n\n \"register definitions\",\n\n (\"regDef\",),\n (\"F_Noop\", 0, 1, 1, \"reg 0\"),\n\n \"status registers\",\n\n (\"F_Rd_Status\", None, 1, 4, \"status reg\"),\n (\"F_Rd_Inputs\", None, 1, 4, \"inputs reg\"),\n\n \"control registers\",\n\n (\"F_Ld_Run_Ctl\", None, 1, 1, \"run control reg\"),\n (\"F_Ld_Sync_Ctl\", None, 1, 1, \"sync control reg\"),\n (\"F_Ld_Cfg_Ctl\", None, 1, 3, \"config control reg\"),\n (\"F_Ld_Clk_Ctl\", None, 1, 1, \"clock control reg\"),\n (\"F_Ld_Dsp_Reg\", None, 1, 1, \"display reg\"),\n\n \"controller\",\n\n (\"F_Ctrl_Base\", None, \"controller\", None, \"controller\"),\n\n \"reader\",\n\n (\"F_Read_Base\", None, \"reader\", None, \"reader\"),\n\n \"debug frequency control\",\n\n (\"F_Dbg_Freq_Base\", None, \"dbgFreq\", None, \"dbg frequency\"),\n\n \"spindle speed\",\n\n (\"F_Rd_Idx_Clks\", None, 1, 4, \"clocks per index\"),\n\n \"step spindle frequency generator\",\n\n \"pwm\",\n\n (\"F_PWM_Base\", None, \"pwmCtl\", None, \"pwm control\"),\n\n \"base for modules\",\n\n (\"F_Enc_Base\", None, \"encoder\", None, \"encoder registers\"),\n (\"F_Phase_Base\", None, \"phaseCtl\", None, \"phase registers\"),\n (\"F_ZAxis_Base\", None, \"axisCtl\", None, \"z axis registers\"),\n (\"F_XAxis_Base\", None, \"axisCtl\", None, \"x axis registers\"),\n (\"F_Spindle_Base\", None, \"spindle\", None, \"spindle registers\"),\n (\"F_Cmd_Max\", None, None, None, \"number of commands\"),\n )\n\nxilinxList = \\\n (\n \"skip register zero\",\n\n (\"XNOOP\", \"register 0\"),\n\n \"load control registers\",\n\n (\"XLDZCTL\", \"z control register\"),\n (\"XLDXCTL\", \"x control register\"),\n (\"XLDTCTL\", \"load taper control\"),\n (\"XLDPCTL\", \"position control\"),\n (\"XLDCFG\", \"configuration\"),\n (\"XLDDCTL\", \"load debug control\"),\n (\"XLDDREG\", \"load display reg\"),\n (\"XREADREG\", \"read register\"),\n\n \"status register\",\n\n (\"XRDSR\", \"read status register\"),\n\n \"phase counter\",\n\n (\"XLDPHASE\", \"load phase max\"),\n\n \"load z motion\",\n\n (\"XLDZFREQ\", \"load z frequency\"),\n (\"XLDZD\", \"load z initial d\"),\n (\"XLDZINCR1\", \"load z incr1\"),\n (\"XLDZINCR2\", \"load z incr2\"),\n (\"XLDZACCEL\", \"load z syn accel\"),\n (\"XLDZACLCNT\", \"load z syn acl cnt\"),\n (\"XLDZDIST\", \"load z distance\"),\n (\"XLDZLOC\", \"load z location\"),\n\n \"load x motion\",\n\n (\"XLDXFREQ\", \"load x frequency\"),\n (\"XLDXD\", \"load x initial d\"),\n (\"XLDXINCR1\", \"load x incr1\"),\n (\"XLDXINCR2\", \"load x incr2\"),\n (\"XLDXACCEL\", \"load x syn accel\"),\n (\"XLDXACLCNT\", \"load x syn acl cnt\"),\n (\"XLDXDIST\", \"load x distance\"),\n (\"XLDXLOC\", \"load x location\"),\n\n \"read z motion\",\n\n (\"XRDZSUM\", \"read z sync sum\"),\n (\"XRDZXPOS\", \"read z sync x pos\"),\n (\"XRDZYPOS\", \"read z sync y pos\"),\n (\"XRDZACLSUM\", \"read z acl sum\"),\n (\"XRDZASTP\", \"read z acl steps\"),\n\n \"read x motion\",\n\n (\"XRDXSUM\", \"read x sync sum\"),\n (\"XRDXXPOS\", \"read x sync x pos\"),\n (\"XRDXYPOS\", \"read x sync y pos\"),\n (\"XRDXACLSUM\", \"read x acl sum\"),\n (\"XRDXASTP\", \"read z acl steps\"),\n\n \"read distance\",\n\n (\"XRDZDIST\", \"read z distance\"),\n (\"XRDXDIST\", \"read x distance\"),\n\n \"read location\",\n\n (\"XRDZLOC\", \"read z location\"),\n (\"XRDXLOC\", \"read x location\"),\n\n \"read frequency and state\",\n\n (\"XRDFREQ\", \"read encoder freq\"),\n (\"XCLRFREQ\", \"clear freq register\"),\n (\"XRDSTATE\", \"read state info\"),\n\n \"read phase\",\n\n (\"XRDPSYN\", \"read sync phase val\"),\n (\"XRDTPHS\", \"read tot phase val\"),\n\n \"phase limit info\",\n\n (\"XLDZLIM\", \"load z limit\"),\n (\"XRDZPOS\", \"read z position\"),\n\n \"test info\",\n\n (\"XLDTFREQ\", \"load test freq\"),\n (\"XLDTCOUNT\", \"load test count\"),\n\n \"read control regs\",\n\n (\"XRDZCTL\", \"read control registers\"),\n (\"XRDXCTL\", \"read control registers\")\n )\n\nxilinxBitList = \\\n (\n \"z control register\",\n\n (\"zCtl\",),\n (\"zReset\", 1, 0, \"reset flag\"),\n (\"zStart\", 1, 1, \"start z\"),\n (\"zSrc_Syn\", 1, 2, \"run z synchronized\"),\n (\"zSrc_Frq\", 0, 2, \"run z from clock source\"),\n (\"zDir_In\", 1, 3, \"move z in positive dir\"),\n (\"zDir_Pos\", 1, 3, \"move z in positive dir\"),\n (\"zDir_Neg\", 0, 3, \"move z in negative dir\"),\n (\"zSet_Loc\", 1, 4, \"set z location\"),\n (\"zBacklash\", 1, 5, \"backlash move no pos upd\"),\n (\"zWait_Sync\", 1, 6, \"wait for sync to start\"),\n\n \"x control register\",\n\n (\"xCtl\",),\n (\"xReset\", 1, 0, \"x reset\"),\n (\"xStart\", 1, 1, \"start x\"),\n (\"xSrc_Syn\", 1, 2, \"run x synchronized\"),\n (\"xSrc_Frq\", 0, 2, \"run x from clock source\"),\n (\"xDir_In\", 1, 3, \"move x in positive dir\"),\n (\"xDir_Pos\", 1, 3, \"x positive direction\"),\n (\"xDir_Neg\", 0, 3, \"x negative direction\"),\n (\"xSet_Loc\", 1, 4, \"set x location\"),\n (\"xBacklash\", 1, 5, \"x backlash move no pos upd\"),\n\n \"taper control register\",\n\n (\"tCtl\",),\n (\"tEna\", 1, 0, \"taper enable\"),\n (\"tZ\", 1, 1, \"one for taper z\"),\n (\"tX\", 0, 1, \"zero for taper x\"),\n\n \"position control register\",\n\n (\"pCtl\",),\n (\"pReset\", 1, 0, \"reset position\"),\n (\"pLimit\", 1, 1, \"set flag on limit reached\"),\n (\"pZero\", 1, 2, \"set flag on zero reached\"),\n\n \"configuration register\",\n\n (\"cCtl\",),\n (\"zStep_Pol\", 1, 0, \"z step pulse polarity\"),\n (\"zDir_Pol\", 1, 1, \"z direction polarity\"),\n (\"xStep_Pol\", 1, 2, \"x step pulse polarity\"),\n (\"xDir_Pol\", 1, 3, \"x direction polarity\"),\n (\"enc_Pol\", 1, 4, \"encoder dir polarity\"),\n (\"zPulse_Mult\", 1, 5, \"enable pulse multiplier\"),\n\n \"debug control register\",\n\n (\"dCtl\",),\n (\"Dbg_Ena\", 1, 0, \"enable debugging\"),\n (\"Dbg_Sel\", 1, 1, \"select dbg encoder\"),\n (\"Dbg_Dir\", 1, 2, \"debug direction\"),\n (\"Dbg_Count\", 1, 3, \"gen count num dbg clks\"),\n (\"Dbg_Init\", 1, 4, \"init z modules\"),\n (\"Dbg_Rsyn\", 1, 5, \"running in sync mode\"),\n (\"Dbg_Move\", 1, 6, \"used debug clock for move\"),\n\n \"status register\",\n\n (\"stat\",),\n (\"s_Z_Done_Int\", 1, 0, \"z done interrupt\"),\n (\"s_X_Done_Int\", 1, 1, \"x done interrupt\"),\n (\"s_Dbg_Done\", 1, 2, \"debug done\"),\n (\"s_Z_Start\", 1, 3, \"z start\"),\n (\"s_X_Start\", 1, 4, \"x start\"),\n (\"s_Enc_Dir_In\", 1, 5, \"encoder direction in\"),\n\n \"\"\n )\n\nfpgaEncBitList = \\\n (\n \"run control register\",\n\n (\"rCtl\",),\n (\"ctlReset\", 1, 0, \"reset\"),\n (\"ctlTestClock\", 1, 1, \"testclock\"),\n (\"ctlSpare\", 1, 2, \"spare\"),\n\n \"debug control register\",\n\n (\"dCtl\",),\n (\"DbgEna\", 1, 0, \"enable debugging\"),\n (\"DbgSel\", 1, 1, \"select dbg encoder\"),\n (\"DbgDir\", 1, 2, \"debug direction\"),\n (\"DbgCount\", 1, 3, \"gen count num dbg clks\"),\n\n \"\"\n )\n\nfpgaLatheBitList = \\\n (\n \"status register\",\n\n (\"status\",),\n (\"zAxisEna\", 1, 0, \"z axis enable flag\"),\n (\"zAxisDone\", 1, 1, \"z axis done\"),\n (\"zAxisCurDir\", 1, 2, \"z axis current dir\"),\n (\"xAxisEna\", 1, 3, \"x axis enable flag\"),\n (\"xAxisDone\", 1, 4, \"x axis done\"),\n (\"xAxisCurDir\", 1, 5, \"x axis current dir\"),\n (\"stEStop\", 1, 6, \"emergency stop\"),\n (\"spindleActive\", 1, 7, \"spindle activer\"),\n (\"queNotEmpty\", 1, 8, \"ctl queue not empty\"),\n (\"ctlBusy\", 1, 9, \"controller busy\"),\n (\"syncActive\", 1, 10, \"sync active\"),\n\n \"inputs register\",\n\n (\"inputs\",),\n (\"inZHome\", 1, 0, \"z home switch\"),\n (\"inZMinus\", 1, 1, \"z limit minus\"),\n (\"inZPlus\", 1, 2, \"z Limit Plus\"),\n (\"inXHome\", 1, 3, \"x home switch\"),\n (\"inXMinus\", 1, 4, \"x limit minus\"),\n (\"inXPlus\", 1, 5, \"x Limit Plus\"),\n (\"inSpare\", 1, 6, \"spare input\"),\n (\"inProbe\", 1, 7, \"probe input\"),\n (\"inPin10\", 1, 8, \"pin 10\"),\n (\"inPin11\", 1, 9, \"pin 11\"),\n (\"inPin12\", 1, 10, \"pin 12\"),\n (\"inPin13\", 1, 11, \"pin 13\"),\n (\"inPin15\", 1, 12, \"pin 15\"),\n\n # (\"\", , , \"\"),\n # (\"\", , , \"\"),\n\n \"run control register\",\n (\"run\",),\n (\"runEna\", 1, 0, \"run from controller data\"),\n (\"runInit\", 1, 1, \"initialize controller\"),\n (\"readerInit\", 1, 2, \"initialize reader\"),\n\n # \"command register\",\n # (\"cmd\",),\n # (\"cmdWaitZ\", 1, 0, \"wait for z done\"),\n # (\"cmdWaitX\", 1, 1, \"wait for x done\"),\n\n \"jog control register\",\n (\"jog\",),\n (\"jogContinuous\", 1, 0, \"jog continuous mode\"),\n (\"jogBacklash\", 1, 1, \"jog backlash present\"),\n\n \"axis control register\",\n\n (\"axisCtl\",),\n (\"ctlInit\", 1, 0, \"reset flag\"),\n (\"ctlStart\", 1, 1, \"start\"),\n (\"ctlBacklash\", 1, 2, \"backlash move no pos upd\"),\n (\"ctlWaitSync\", 1, 3, \"wait for sync to start\"),\n (\"ctlDir\", 1, 4, \"direction\"),\n (\"ctlDirPos\", 1, 4, \"move in positive dir\"),\n (\"ctlDirNeg\", 0, 4, \"move in negative dir\"),\n (\"ctlSetLoc\", 1, 5, \"set location\"),\n (\"ctlChDirect\", 1, 6, \"ch input direct\"),\n (\"ctlSlave\", 1, 7, \"slave ctl by other axis\"),\n (\"ctlDroEnd\", 1, 8, \"use dro to end move\"),\n (\"ctlJogCmd\", 1, 9, \"jog with commands\"),\n (\"ctlJogMpg\", 1, 10, \"jog with mpg\"),\n (\"ctlHome\", 1, 11, \"homing axis\"),\n (\"ctlIgnoreLim\", 1, 12, \"ignore limits\"),\n\n \"axis status register\",\n\n (\"axisStatus\",),\n (\"axDoneDist\", 1, 0, \"axis done distance\"),\n (\"axDoneDro\", 1, 1, \"axis done dro\"),\n (\"axDoneHome\", 1, 2, \"axis done home\"),\n (\"axDoneLimit\", 1, 3, \"axis done limit\"),\n\n \"configuration control register\",\n\n (\"cfgCtl\",),\n (\"cfgZDirInv\", 1, 0, \"z dir inverted\"),\n (\"cfgXDirInv\", 1, 1, \"x dir inverted\"),\n (\"cfgZDroInv\", 1, 2, \"z dro dir inverted\"),\n (\"cfgXDroInv\", 1, 3, \"x dro dir inverted\"),\n (\"cfgZJogInv\", 1, 4, \"z jog dir inverted\"),\n (\"cfgXJogInv\", 1, 5, \"x jog dir inverted\"),\n (\"cfgSpDirInv\", 1, 6, \"spindle dir inverted\"),\n\n (\"cfgZHomeInv\", 1, 7, \"z home inverted\"),\n (\"cfgZMinusInv\", 1, 8, \"z minus inverted\"),\n (\"cfgZPlusInv\", 1, 9, \"z plus inverted\"),\n\n (\"cfgXHomeInv\", 1, 10, \"x home inverted\"),\n (\"cfgXMinusInv\", 1, 11, \"x minus inverted\"),\n (\"cfgXPlusInv\", 1, 12, \"x plus inverted\"),\n\n (\"cfgProbeInv\", 1, 13, \"probe inverted\"),\n\n (\"cfgEncDirInv\", 1, 14, \"invert encoder dir\"),\n (\"cfgEStopEna\", 1, 15, \"estop enable\"),\n (\"cfgEStopInv\", 1, 16, \"estop invert\"),\n (\"cfgEnaEncDir\", 1, 17, \"enable encoder dir\"),\n (\"cfgGenSync\", 1, 18, \"generate sync pulse\"),\n (\"cfgPWMEna\", 1, 19, \"pwm enable\"),\n\n \"clock control register\",\n\n (\"clkCtl\",),\n (\"zFreqSel\", None, (2, 0), \"z Frequency select\"),\n (\"xFreqSel\", None, (5, 3), \"x Frequency select\"),\n\n # \"clock selection values\",\n\n (\"clkNone\", 0, (2, 0), \"\"),\n (\"clkFreq\", 1, (2, 0), \"\"),\n (\"clkCh\", 2, (2, 0), \"\"),\n (\"clkIntClk\", 3, (2, 0), \"\"),\n (\"clkSlvFreq\", 4, (2, 0), \"\"),\n (\"clkSlvCh\", 5, (2, 0), \"\"),\n (\"clkSpindle\", 6, (2, 0), \"\"),\n (\"clkDbgFreq\", 7, (2, 0), \"\"),\n\n # \"z clock values\",\n\n (\"zClkNone\", 0, (2, 0), \"\"),\n (\"zClkZFreq\", 1, (2, 0), \"\"),\n (\"zClkCh\", 2, (2, 0), \"\"),\n (\"zClkIntClk\", 3, (2, 0), \"\"),\n (\"zClkXFreq\", 4, (2, 0), \"\"),\n (\"zClkXCh\", 5, (2, 0), \"\"),\n (\"zClkSpindle\", 6, (2, 0), \"\"),\n (\"zClkDbgFreq\", 7, (2, 0), \"\"),\n\n # \"x clock values\",\n\n (\"xClkNone\", 0, (5, 3), \"\"),\n (\"xClkXFreq\", 1, (5, 3), \"\"),\n (\"xClkCh\", 2, (5, 3), \"\"),\n (\"xClkIntClk\", 3, (5, 3), \"\"),\n (\"xClkZFreq\", 4, (5, 3), \"\"),\n (\"xClkZCh\", 5, (5, 3), \"\"),\n (\"xClkSpindle\", 6, (5, 3), \"\"),\n (\"xClkDbgFreq\", 7, (5, 3), \"\"),\n\n (\"clkDbgFreqEna\", 1, 6, \"enable debug frequency\"),\n\n \"sync control register\",\n\n (\"synCtl\",),\n (\"synPhaseInit\", 1, 0, \"init phase counter\"),\n (\"synEncInit\", 1, 1, \"init encoder\"),\n (\"synEncEna\", 1, 2, \"enable encoder\"),\n\n \"spindle control register\",\n\n (\"spCtl\",),\n (\"spInit\", 1, 0, \"spindle init\"),\n (\"spEna\", 1, 1, \"spindle enable\"),\n (\"spDir\", 1, 2, \"spindle direction\"),\n (\"spJogEnable\", 1, 3, \"spindle jog enable\"),\n\n \"\",\n # (\"\",),\n # (\"\", , , \"\"),\n\n # \"\",\n # (\"\",),\n # (\"\", , , \"\"),\n )\n\nenumList = \\\n (\n # \"z control states\",\n\n # \"enum z_States\",\n # \"{\",\n # (\"ZIDLE\", \"idle\"),\n # (\"ZWAITBKLS\", \"wait for backlash move complete\"),\n # (\"ZSTARTMOVE\", \"start z move\"),\n # (\"ZWAITMOVE\", \"wait for move complete\"),\n # (\"ZDELAY\", \"wait for position to settle\"),\n # (\"ZDONE\", \"clean up state\"),\n # \"};\",\n\n # \"x control states\",\n\n # \"enum x_States\",\n # \"{\",\n # (\"XIDLE\", \"idle\"),\n # (\"XWAITBKLS\", \"wait for backlash move complete\"),\n # (\"XSTARTMOVE\", \"start x move\"),\n # (\"XWAITMOVE\", \"wait for move complete\"),\n # (\"XDELAY\", \"wait for position to settle\"),\n # (\"XDONE\", \"clean up state\"),\n # \"};\",\n\n \"axis control states\",\n\n \"enum axis_States\",\n \"{\",\n (\"AXIS_IDLE\", \"idle\"),\n (\"AXIS_WAIT_BACKLASH\", \"wait for backlash move complete\"),\n (\"AXIS_START_MOVE\", \"start axis move\"),\n (\"AXIS_WAIT_MOVE\", \"wait for move complete\"),\n (\"AXIS_DELAY\", \"wait for position to settle\"),\n (\"AXIS_DONE\", \"clean up state\"),\n (\"AXIS_STATES\", \"number of states\"),\n \"};\",\n\n \"move control states\",\n\n \"enum m_States\",\n \"{\",\n (\"M_IDLE\", \"idle state\"),\n (\"M_WAIT_Z\", \"wait for z to complete\"),\n (\"M_WAIT_X\", \"wait for x to complete\"),\n (\"M_WAIT_SPINDLE\", \"wait for spindle start\"),\n (\"M_WAIT_SYNC_PARMS\", \"wait for sync parameters\"),\n (\"M_WAIT_SYNC_CMD\", \"wait for sync command\"),\n (\"M_START_SYNC\", \"start sync\"),\n (\"M_WAIT_SYNC_READY\", \"wait for sync\"),\n (\"M_WAIT_SYNC_DONE\", \"wait for sync done\"),\n (\"M_WAIT_MEASURE_DONE\", \"wait for measurement done\"),\n (\"M_WAIT_PROBE\", \"wait for probe to complete\"),\n (\"M_WAIT_MEASURE\", \"wait for measurement to complete\"),\n (\"M_WAIT_SAFE_X\", \"wait for move to safe x to complete\"),\n (\"M_WAIT_SAFE_Z\", \"wait for move to safe z to complete\"),\n (\"M_WAIT_ARC\", \"wait for arc move to complete\"),\n \"};\",\n\n \"move control commands\",\n\n \"enum m_Commands\",\n \"{\",\n (\"MOVE_Z\", \"move z\"),\n (\"MOVE_X\", \"move x\"),\n (\"SAVE_Z\", \"save z\"),\n (\"SAVE_X\", \"save x\"),\n (\"SAVE_Z_OFFSET\", \"save z offset\"),\n (\"SAVE_X_OFFSET\", \"save x offset\"),\n (\"SAVE_TAPER\", \"save taper\"),\n (\"MOVE_Z_X\", \"move x in sync with z\"),\n (\"MOVE_X_Z\", \"move z in sync with x\"),\n (\"TAPER_Z_X\", \"taper x\"),\n (\"TAPER_X_Z\", \"taper z\"),\n (\"START_SPINDLE\", \"spindle start\"),\n (\"STOP_SPINDLE\", \"spindle stop\"),\n (\"Z_SYN_SETUP\", \"z sync setup\"),\n (\"X_SYN_SETUP\", \"x sync setup\"),\n (\"SEND_SYNC_PARMS\", \"send sync parameters\"),\n (\"SYNC_COMMAND\", \"send sync command\"),\n (\"PASS_NUM\", \"set pass number\"),\n (\"QUE_PAUSE\", \"pause queue\"),\n (\"MOVE_Z_OFFSET\", \"move z offset\"),\n (\"SAVE_FEED_TYPE\", \"save feed type\"),\n (\"Z_FEED_SETUP\", \"setup z feed\"),\n (\"X_FEED_SETUP\", \"setup x feed\"),\n (\"SAVE_FLAGS\", \"save thread flags\"),\n (\"PROBE_Z\", \"probe in z direction\"),\n (\"PROBE_X\", \"probe in x direction\"),\n (\"SAVE_Z_DRO\", \"save z dro reading\"),\n (\"SAVE_X_DRO\", \"save x dro reading\"),\n (\"QUE_PARM\", \"save parameter in queue\"),\n (\"MOVE_ARC\", \"move in an arc\"),\n (\"OP_DONE\", \"operation done\"),\n \"};\",\n\n \"move control operation\",\n\n \"enum operations\",\n \"{\",\n (\"OP_TURN\", \"turn\"),\n (\"OP_FACE\", \"face\"),\n (\"OP_CUTOFF\", \"cutoff\"),\n (\"OP_TAPER\", \"taper\"),\n (\"OP_THREAD\", \"thread\"),\n (\"OP_ARC\", \"arc\"),\n \"};\",\n\n \"home control states\",\n\n \"enum h_States\",\n \"{\",\n (\"H_IDLE\", \"idle state\"),\n (\"H_HOME\", \"found home switch\"),\n (\"H_OFF_HOME\", \"off home switch\"),\n (\"H_BACKOFF\", \"backoff dist from switch\"),\n (\"H_SLOW\", \"found home slowly\"),\n # (\"H_\", \"\"),\n \"};\",\n\n \"debug message types\",\n\n \"enum d_Message\",\n \"{\",\n (\"D_PASS\", \"pass done\"),\n (\"D_DONE\", \"all operations done\"),\n (\"D_TEST\", \"test message\"),\n\n (\"D_XMOV\", \"x move location\"),\n (\"D_XLOC\", \"x location\"),\n (\"D_XDST\", \"x distance\"),\n (\"D_XSTP\", \"x steps\"),\n (\"D_XST\", \"x state\"),\n (\"D_XBSTP\", \"x backlash steps\"),\n (\"D_XDRO\", \"x dro location\"),\n (\"D_XPDRO\", \"x pass dro location\"),\n (\"D_XEXP\", \"x expected location\"),\n (\"D_XERR\", \"x error with respect to dro\"),\n (\"D_XWT\", \"x wait\"),\n (\"D_XDN\", \"x done\"),\n (\"D_XEST\", \"x spindle encoder start count\"),\n (\"D_XEDN\", \"x spindle encoder done count\"),\n (\"D_XX\", \"x \"),\n (\"D_XY\", \"x \"),\n\n (\"D_ZMOV\", \"z move location\"),\n (\"D_ZLOC\", \"z location\"),\n (\"D_ZDST\", \"z distance\"),\n (\"D_ZSTP\", \"z steps\"),\n (\"D_ZST\", \"z state\"),\n (\"D_ZBSTP\", \"z backlash steps\"),\n (\"D_ZDRO\", \"z dro location\"),\n (\"D_ZPDRO\", \"z pass dro location\"),\n (\"D_ZEXP\", \"z expected location\"),\n (\"D_ZERR\", \"z error with respect to dro\"),\n (\"D_ZWT\", \"z wait\"),\n (\"D_ZDN\", \"z done\"),\n (\"D_ZEST\", \"z spindle encoder start count\"),\n (\"D_ZEDN\", \"Z spindle encoder done count\"),\n (\"D_ZX\", \"z \"),\n (\"D_ZY\", \"z \"),\n\n (\"D_XIDXD\", \"x dro at index pulse\"),\n (\"D_XIDXP\", \"x position at index pulse\"),\n (\"D_ZIDXD\", \"z dro at index pulse\"),\n (\"D_ZIDXP\", \"z position at index pulse\"),\n\n (\"D_HST\", \"home state\"),\n\n (\"D_MSTA\", \"move state\"),\n (\"D_MCMD\", \"move command\"),\n \"};\",\n\n \"pylathe update events\",\n\n \"enum ev_Events\",\n \"{\",\n (\"EV_ZLOC\", \"z location\"),\n (\"EV_XLOC\", \"x location\"),\n (\"EV_RPM\", \"rpm\"),\n (\"EV_READ_ALL\", \"all values\"),\n (\"EV_ERROR\", \"event error\"),\n (\"EV_MAX\", \"maximum event\"),\n # (\"EV_\", \"\"),\n \"};\",\n\n \"turning sync selector\",\n\n \"enum sel_Turn c\",\n \"{\",\n (\"SEL_TU_SPEED\", \"Motor Speed\"),\n (\"SEL_TU_STEP\", \"Stepper\"),\n (\"SEL_TU_ENC\", \"Encoder\"),\n (\"SEL_TU_ISYN\", \"Int Syn\"),\n (\"SEL_TU_ESYN\", \"Ext Syn\"),\n (\"SEL_TU_SYN\", \"Sync\"),\n \"};\",\n\n \"threading sync selector\",\n\n \"enum sel_Thread c\",\n \"{\",\n (\"SEL_TH_NO_ENC\", \"No Encoder\"),\n (\"SEL_TH_STEP\", \"Stepper\"),\n (\"SEL_TH_ENC\", \"Encoder\"),\n (\"SEL_TH_ISYN_RENC\", \"Int Syn, Runout Enc\"),\n (\"SEL_TH_ESYN_RENC\", \"Ext Syn, Runout Enc\"),\n (\"SEL_TH_ESYN_RSYN\", \"Ext Syn, Runout Syn\"),\n (\"SEL_TH_SYN\", \"Syn, Runout Syn\"),\n \"};\",\n\n \"arc config selector\",\n\n \"enum sel_Arc_Type c\",\n \"{\",\n (\"SEL_ARC_END\", \"End\"),\n (\"SEL_ARC_CORNER\", \"Corner\"),\n (\"SEL_ARC_SMALL\", \"Small Ball\"),\n (\"SEL_ARC_LARGE\", \"Large Ball\"),\n (\"SEL_ARC_SMALL_STEM\", \"Small Stem\"),\n (\"SEL_ARC_LARGE_STEM\", \"Large Stem\"),\n \"};\",\n )\n\nmegaEnumList = \\\n (\n \"mega poll response bits\",\n\n \"enum poll_Mega\",\n \"{\",\n (\"M_POLL_ESTOP_NO\", \"estop no in\"),\n (\"M_POLL_ESTOP_NC\", \"estop nc in\"),\n (\"M_POLL_SP_FWD\", \"spindle forward in\"),\n (\"M_POLL_SP_REV\", \"spindle reverse in\"),\n (\"M_POLL_ESTOP\", \"estop condition\"),\n (\"M_POLL_WD_ENA\", \"watchdog enabled\"),\n (\"M_POLL_CP_ACTIVE\", \"charge pump active\"),\n (\"M_POLL_PWM_ACTIVE\", \"pwm active\"),\n (\"M_POLL_STEP_DIS\", \"stepper disabled\"),\n (\"M_POLL_ESTOP_RLY\", \"estop relay\"),\n (\"M_POLL_ESTOP_PC\", \"estop pc\"),\n # (\"M_POLL_\", \"\"),\n \"};\",\n\n \"mega vfd speed selector\",\n\n \"enum vfdSpeed c\",\n \"{\",\n (\"MEGA_SLOW_PWM\", \"Slow PWM\"),\n (\"MEGA_FAST_PWM\", \"Fast PWM\"),\n (\"MEGA_DIRECT_RPM\", \"Set RPM\"),\n \"};\",\n )\n\nxilinxEncList = \\\n (\n \"skip register zero\",\n\n (\"XNOOP\", \"register 0\"),\n\n \"load control registers\",\n )\n\nif __name__ == '__main__':\n import os\n from setup import Setup\n from sys import stderr, stdout\n from platform import system\n\n # print os.path.realpath(__file__)\n # print os.getcwd()\n\n R_PI = False\n WINDOWS = system() == 'Windows'\n if WINDOWS:\n from pywinusb.hid import find_all_hid_devices\n # from comm import Comm, CommTimeout\n from commPi import Comm, CommTimeout\n\n R_PI = True\n else:\n if not os.uname().machine.startswith('arm'):\n from comm import Comm, CommTimeout\n else:\n from commPi import Comm, CommTimeout\n\n R_PI = True\n\n fData = True\n if WINDOWS:\n path = os.path.dirname(os.path.realpath(__file__))\n\n cLoc = path + '/../LatheCPP/include/'\n syncLoc = path + '/../SyncCPP/include/'\n megaLoc = path + '/../../Arduino/output/'\n\n xLoc = path + '/../../Xilinx/LatheCtl/'\n fEncLoc = path + '/../../Altera/Encoder/VHDL/'\n fLatheLoc = path + '/../../Altera/LatheNew/VHDL/'\n else:\n path = os.path.dirname(os.path.realpath(__file__))\n\n cLoc = path + '/../LatheCPP/include/'\n syncLoc = path + '/../SyncCPP/include/'\n megaLoc = path + '/../../Arduino/output/'\n\n xLoc = path + '/../Xilinx/LatheCtl/'\n fEncLoc = path + '/../Altera/Encoder/VHDL/'\n fLatheLoc = path + '/../Altera/LatheNew/VHDL/'\n\n # print(\"creating interface files\")\n setup = Setup()\n setup.file = True\n setup.createConfig(configList)\n setup.createStrings(strList)\n\n setup.createCommands(cmdList, cLoc, fData)\n\n setup.createCommands(syncCmdList, cLoc, fData, prefix='sync')\n setup.createCommands(syncCmdList, syncLoc, fData,\n pyFile=False, check=False, prefix='sync')\n\n setup.createCommands(megaCmdList, cLoc, fData, prefix='mega',\n pyFile=False)\n setup.createCommands(megaCmdList, megaLoc, fData,\n pyFile=False, check=False, prefix='mega')\n\n setup.createParameters(parmList, cLoc, fData)\n\n setup.createParameters(syncParmList, cLoc, fData, prefix='sync',\n cSource=None)\n setup.createParameters(syncParmList, syncLoc, fData, pyFile=False,\n cSource='../src/', prefix='sync')\n\n setup.createParameters(megaParmList, cLoc, fData, pyFile=False,\n cSource=None, prefix='mega')\n setup.createParameters(megaParmList, megaLoc, fData, pyFile=True,\n cSource='', prefix='mega')\n\n setup.createEnums(enumList, cLoc, fData)\n\n setup.createEnums(megaEnumList, cLoc, fData, pyFile=True,\n prefix=\"mega\")\n setup.createEnums(megaEnumList, megaLoc, fData, pyFile=False,\n prefix=\"mega\")\n\n setup.createCtlBits(regList, cLoc, fData)\n\n setup.createFpgaReg(xilinxList, cLoc, xLoc, fData)\n setup.createFpgaBits(xilinxBitList, cLoc, xLoc, fData)\n\n setup.createFpgaReg(fpgaEncList, cLoc, fEncLoc, fData,\n pName=\"eRegDef\", cName=\"fpgaEnc\")\n setup.createFpgaBits(fpgaEncBitList, cLoc, fEncLoc, fData,\n pName=\"fpgaEnc\", cName=\"fpgaEnc\",\n package=\"FpgaEncBits\", xName=\"FpgaEnc\")\n\n setup.createFpgaReg(fpgaLatheList, cLoc, fLatheLoc, fData,\n pName=\"lRegDef\", cName=\"fpgaLatheReg\")\n setup.createFpgaBits(fpgaLatheBitList, cLoc, fLatheLoc, fData,\n pName=\"fpgaLathe\", cName=\"fpgaLatheBits\",\n package=\"FpgaLatheBits\", xName=\"FpgaLathe\")\n stdout.flush()\n stderr.flush()\n\n # xLoc = path + '/../../Xilinx/Spartan6LedTest/'\n\n # setup.createFpgaReg(xilinxEncList, cLoc, xLoc, fData, \\\n # pName=\"xEncRegDef\", \\\n # table=\"encRegTable\", \\\n # cName=\"Enc\", \\\n # xName=\"encRegDef\" )\n\n # setup.createFpgaBits(xilinxEncBitList, cLoc, xLoc, fData, \\\n # pName=\"xEncBitDef\", \\\n # xName=\"xEnc\", \\\n # package=\"xEncBits\", \\\n # cName=\"xEnc\")\n","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":68810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"9683535","text":"import argparse, sys, os\nimport torch\nfrom torchtext import data\nfrom torchtext import datasets\nfrom torchtext.vocab import Vectors, GloVe\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom nltk.tokenize import word_tokenize\nfrom models.LSTM import LSTMClassifier\nimport numpy as np\nimport pickle\n\ndef main(args):\n batch_size = 32\n output_size = 2\n hidden_size = 256\n embedding_length = 300\n\n tokenize = lambda x: x.split()\n TEXT = data.Field(sequential=True, tokenize=tokenize, lower=True, include_lengths=True, batch_first=True, fix_length=50)\n LABEL = data.LabelField(tensor_type=torch.FloatTensor)\n train_data = data.TabularDataset(path=args.train_data_tsv_file, format='tsv',fields=[('text', TEXT),('label', LABEL)], skip_header=True)\n TEXT.build_vocab(train_data, vectors=GloVe('840B', 300))\n LABEL.build_vocab(train_data)\n word_embeddings = TEXT.vocab.vectors\n vocab_size = len(TEXT.vocab)\n \n model = LSTMClassifier(batch_size, output_size, hidden_size, vocab_size, embedding_length, word_embeddings)\n model.load_state_dict(torch.load(args.saved_model_path))\n model.cuda()\n model.eval()\n for segments_pkl in os.listdir(args.transcript_segments_folder):\n print(segments_pkl)\n all_segments = pickle.load(open(os.path.join(args.transcript_segments_folder, segments_pkl), 'rb'))\n readable_output_file = open(os.path.join(args.output_transcript_segments_folder, os.path.splitext(segments_pkl)[0]+'.tsv'), 'w')\n for video_id, segments in all_segments.items():\n for i in range(len(segments)):\n sentence = word_tokenize(segments[i]['transcript'].lower())\n test_sent = [[TEXT.vocab.stoi[x] for x in sentence]]\n test_sent = np.asarray(test_sent)\n test_sent = torch.LongTensor(test_sent)\n test_tensor = Variable(test_sent, volatile=True).cuda()\n output = model(test_tensor, 1)\n out = F.softmax(output, 1)\n if (torch.argmax(out[0]) == 1):\n pred_label = 0\n else:\n pred_label = 1\n segments[i]['is_background'] = pred_label \n all_segments[video_id][i] = segments[i]\n readable_output_file.write('%s\\t%d\\n' % (' '.join(sentence), pred_label))\n pickle.dump(all_segments, open(os.path.join(args.output_transcript_segments_folder, segments_pkl), 'wb'))\n \nif __name__ == \"__main__\":\n argparser = argparse.ArgumentParser(sys.argv[0])\n argparser.add_argument(\"--train_data_tsv_file\", type = str)\n argparser.add_argument(\"--saved_model_path\", type = str)\n argparser.add_argument(\"--transcript_segments_folder\", type = str)\n argparser.add_argument(\"--output_transcript_segments_folder\", type = str)\n args = argparser.parse_args()\n print (args)\n print (\"\")\n main(args)\n\n","sub_path":"run_classifier.py","file_name":"run_classifier.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"617143289","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 9 16:08:11 2020\n\n@author: nooteboom\n\"\"\"\n\nimport os\nassert os.environ['CONDA_DEFAULT_ENV']=='Cartopy-py32', 'You should use the conda environment Cartopy-py3'\nimport numpy as np\nimport matplotlib.pylab as plt\nimport cartopy.crs as ccrs\nimport seaborn as sns\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\nimport matplotlib.ticker as mticker\nfrom matplotlib.lines import Line2D\nimport cartopy.feature as cfeature\n\n\nif(__name__=='__main__'):\n sns.set(context='paper', style='whitegrid')\n sp = 6 # the sinking speed (m/day)\n mins = 300 # The variable s_{min} that is used for subplots (a) and (b)\n fs = 28 # the fontsize for plotting\n si=8 # the markersize for plotting\n # Set the color bounds for the reachability (vmin and vmax)\n if(sp==6):\n vs = np.array([7000,20000]) / 1000\n elif(sp==25):\n vs = np.array([7000,13000]) / 1000\n elif(sp==250):\n vs = np.array([7000,14000]) / 1000\n elif(sp==11):\n vs = np.array([7000,15000]) / 1000\n markers = 10 # another markersize for plotting\n noisecolor = 'k' # the color for plotting\n #%% Load the OPTICS result\n dirr = 'OPTICSresults/'\n ff = np.load(dirr+'OPTICS_sp%d_smin%d.npz'%(sp, mins))\n lon0 = ff['lon']\n lat0 = ff['lat']\n reachability = ff['reachability'] / 1000\n ordering = ff['ordering']\n #%%\n exte=[18, 360-70, -75, 75]; latlines=[-75,-50, -25, 0, 25, 50, 75, 100];\n \n f = plt.figure(constrained_layout=True, figsize = (17, 13))\n gs = f.add_gridspec(2, 8)\n \n ax = f.add_subplot(gs[0,:5],projection=ccrs.PlateCarree())\n ax.set_title('(a)', fontsize=fs)\n ax.add_feature(cfeature.LAND, zorder=10)\n ax.add_feature(cfeature.COASTLINE, zorder=10)\n g = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,\n linewidth=1, color='gray', alpha=0.5, linestyle='--')\n g.xlocator = mticker.FixedLocator([-180,-90, -0, 90, 181])\n g.xlabels_top = False\n g.ylabels_right = False\n g.xlabel_style = {'fontsize': fs}\n g.ylabel_style = {'fontsize': fs}\n g.xformatter = LONGITUDE_FORMATTER\n g.yformatter = LATITUDE_FORMATTER\n g.ylocator = mticker.FixedLocator(latlines)\n \n ax.set_extent(exte, ccrs.PlateCarree())\n p = ax.scatter(lon0, lat0, s=25, c=reachability, cmap = 'inferno',\n alpha=0.6, vmin=vs[0], vmax=vs[1])\n \n cbar = plt.colorbar(p, shrink=.8, aspect=10, orientation='horizontal', \n extend='both')\n cbar.set_label(label='Reachability ($10^{-3}\\cdot r(p_i)$)', fontsize=fs-10)\n cbar.ax.tick_params(labelsize=11) \n \n ax = f.add_subplot(gs[0,5:])\n ax.yaxis.set_label_position(\"right\")\n ax.yaxis.tick_right()\n \n ax.scatter(np.arange(len(reachability)), \n reachability[ordering], \n c=noisecolor, \n marker=\"o\", s=5, alpha=0.1)\n ax.set_title('(b)', size=10, fontsize=fs)\n ax.set_ylabel(r\"Reachability ($10^{-3}\\cdot r(p_i)$)\", fontsize=fs)\n ax.set_xlabel(r\"Sediment location #$i$\", fontsize=fs-3)\n ax.tick_params(labelsize=fs)\n \n #%% Mantel part\n minss = [100, 200, 300, 400, 500, 600,700,800,900, 1000] # s_min values\n perm = 999\n def load_mantel(dist1 = 'reach', dist2 = 'tax', distc = 'site'):\n if(distc=='env'):\n envs = ['temp']#,'N']\n else:\n envs = ['temp']\n stenv = ''\n for i in envs: stenv+=i;\n ff = np.load('manteltest_results/mantel_tests%s%s_constant%s%s_sp%d_perm%d.npz'%(dist1,dist2,\n distc,stenv,\n sp,perm))\n return ff\n\n ff = load_mantel()\n DR = ff['DR'] # Dinocyst R-statistics\n DP = ff['DP'] # Dinocyst p-value\n FR = ff['FR'] # Foraminifera R-statistics\n FP = ff['FP'] # Foraminifera p-value\n \n ff = load_mantel(dist2 = 'env')\n DRe = ff['DR'] # Dinocyst R-statistics\n DPe = ff['DP'] # Dinocyst p-value\n FRe = ff['FR'] # Foraminifera R-statistics\n FPe = ff['FP'] # Foraminifera p-value\n \n plt.rcParams['axes.axisbelow'] = True\n lw = 3\n si = 10\n \n custom_lines = [Line2D([0], [0],linestyle='--', color='k', \n lw=lw, marker='o', markersize=si),\n Line2D([0], [0],linestyle='-', color='k', \n lw=lw, marker='o', markersize=si)]\n\n custom_lines2 = [Line2D([0], [0],linestyle='-', color='red', \n lw=lw, marker='o', markersize=si),\n Line2D([0], [0],linestyle='-', color='k', \n lw=lw, marker='o', markersize=si)]\n \n ticks1 = [0,0.1,0.2,0.3, 0.4, 0.5]\n \n ax = f.add_subplot(gs[1,2:-2])\n ax2 = ax.twinx()\n \n color = 'red'\n color2 = 'k'\n ax.set_ylabel('correlation \\n (partial Mantel)', color=color2, fontsize=fs)\n ax.plot(minss,DRe,'--o', color=color2, lw=lw, markersize=si)\n ax.plot(minss,FRe,'-o', color=color2, lw=lw, markersize=si, label='')\n ax.plot(minss,DR,'--o', color=color, lw=lw, markersize=si)\n ax.plot(minss,FR,'-o', color=color, lw=lw, markersize=si, label='')\n ax.tick_params(axis='y', labelcolor=color2)\n ax.set_yticks(ticks1)\n ax.set_yticklabels(ticks1, fontsize=fs)\n ax.set_ylim(-0.01,0.52)\n ax.set_xlabel('$s_{min}$', fontsize=fs)\n ax.set_title('(c)', size=10, fontsize=fs)\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(fs) \n \n ax.legend(custom_lines, ['dinocysts','foraminifera'], \n fontsize=fs, loc='upper left', bbox_to_anchor=(1.05, 0.9))\n ax2.legend(custom_lines2, ['taxonomy','SST'], \n fontsize=fs, loc='upper left', bbox_to_anchor=(1.05, 0.4))\n ax2.get_yaxis().set_visible(False)\n \n #%% save figure\n \n f.savefig(\"figs/reach_mins%d_Mantel_sp%d\"%(mins,sp), dpi=300, bbox_inches='tight')\n plt.show()\n","sub_path":"OPTICS/figure3.py","file_name":"figure3.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"296988222","text":"from data import get_csv\nfrom collections import deque\nfrom math import exp, log\nfrom datetime import datetime\nfrom statistics import median \n\n\ndef parse():\n from template import by_block, by_month\n #setup output list with keys as first element\n block_output = [[i] for i in list(by_block.keys())]\n month_output = [[i] for i in list(by_month.keys())]\n \n #import data from csv\n blocks = get_csv(\"blocks\")[::-1]\n price = get_csv(\"price\")[::-1]\n reddit = get_csv(\"reddit\")[::-1]\n price_btc = get_csv(\"price_btc\")[::-1]\n price_xmr = get_csv(\"price_xmr\")[::-1]\n \n by_month['timestamp'] = blocks[-1][0]\n \n #initiate price\n p = price.pop() \n p_btc = price_btc.pop() \n p_xmr = price_xmr.pop() \n \n \n #stacks for fast processing\n day = deque([])\n month = deque([])\n year = deque([])\n nonces = deque([])\n \n #nonce uniformity constants\n #there are 2160 nonces and 2160 bins\n max_nonce=2**32\n bin_size = int((max_nonce)/(360*3))\n #we count how many nonces are in each bin\n bin_count = [0 for i in range((2**32)//(bin_size)+1)]\n #the number of bins with exactly 1 nonce should be about 1/e\n singleton_bins = 0\n locked_txs=[]\n \n #block reward over 1y\n reward_1y = 0\n block_count = 0\n while blocks:\n #block data\n x = blocks.pop()\n if blocks and len(blocks)%int(blocks[0][1]/100)==0:\n print(int(x[1]))\n\n #locked_txs\n if len(x[10])>0:\n locked_txs = locked_txs + [list(y) for y in x[10]]\n by_block['supply_locked'] += sum([y[0] for y in x[10]])\n new_locked_txs = []\n while locked_txs:\n tx = locked_txs.pop()\n if tx[1] > 500000000 and tx[1] < x[0]:\n by_block['supply_locked'] -= tx[0]\n elif tx[1] == 1:\n by_block['supply_locked'] -= tx[0]\n elif tx[1]< by_block['timestamp']:\n tx[1] = int(tx[1] - 1)\n new_locked_txs.append(tx)\n else:\n new_locked_txs.append(tx)\n locked_txs=new_locked_txs\n \n #no-calculation data\n by_block['timestamp'] = x[0]\n by_block['block_height'] = int(x[1])\n by_block['version'] = str(int(x[8]))+\".\"+str(int(x[9]))\n by_block['supply_total'] += x[3]\n by_block['supply_circulating'] = by_block['supply_total']-by_block['supply_locked']\n by_block['block_size_cum'] += x[6]\n by_block['block_difficulty'] = x[2]\n by_block['block_reward'] = x[3]\n \n day.append(x[0]) \n by_block['block_count_24h'] += 1\n while day[0] < x[0] - 24*60*60:\n head = day.popleft()\n by_block['block_count_24h'] -= 1\n \n #price\n while p[0] < x[0] and price:\n p = price.pop()\n by_block['price'] = p[1]\n if(by_block['price'] != None):\n by_block['marketcap']=by_block['supply_total']*by_block['price']\n if(by_month['miner_revenue'] == None):\n by_month['miner_revenue'] = 0\n by_month['miner_revenue'] += (x[3]+x[5])*by_block['price']\n else:\n by_month['miner_revenue'] = None\n \n #btc_price\n while p_btc[0] < x[0] and price_btc:\n p_btc = price_btc.pop()\n by_block['price_btc'] = p_btc[1]\n if(by_block['price_btc'] != None):\n by_block['marketcap_btc']=by_block['supply_total']*by_block['price_btc']\n \n #xmr_price\n while p_xmr[0] < x[0] and price_xmr:\n p_xmr = price_xmr.pop()\n by_block['price_xmr'] = p_xmr[1]\n if( by_block['price_xmr'] != None):\n by_block['marketcap_xmr']=by_block['supply_total']*by_block['price_xmr']\n \n \n by_month['fee'] += x[5]\n by_month['tx'] += x[4]\n by_month['volume'] += x[13]/(1.0*10**12)\n by_month['block_size'] += x[6]\n by_month['inputs'] += x[11]\n by_month['outputs'] += x[12]\n by_month['outputs_inputs'] += (x[12]-x[11])\n \n #reddit\n while reddit and reddit[-1][0] < x[0] :\n submission = reddit.pop()\n by_month['reddit_posts'] += 1\n by_month['reddit_comments'] += submission[1]\n \n #inflation 1y %\n year.append([x[0],x[3]])\n reward_1y += x[3]\n while year[0][0] < x[0] - 365*24*60*60:\n amt = year.popleft()\n reward_1y -= amt[1]\n by_block['inflation_1Y'] = reward_1y / by_block['supply_total']\n \t \n #nonce uniformity\n #calculate which bin the nonce belongs in like a histogram\n if by_block['block_height']>=1146200:\n #nonce uniformity constants\n #there are 2160 nonces and 2160 bins\n max_nonce = 2**64\n bin_size = int((max_nonce)/(360*3))\n nonce = int(x[7])//bin_size\n #add to memory\n nonces.append(nonce)\n #put nonce into bin\n bin_count[nonce] += 1\n #recalculate bins with exactly one\n if bin_count[nonce] == 1:\n singleton_bins += 1 \n elif bin_count[nonce] == 2:\n singleton_bins -= 1 \n if len(nonces)> 360*3: \n #remove nonce and recalculate\n nonce = nonces.popleft() \n bin_count[nonce] -= 1\n if bin_count[nonce] == 1:\n singleton_bins += 1 \n elif bin_count[nonce] == 0:\n singleton_bins -= 1\n #assuming the nonces are uniformly random, singleton_bins / 2160 == 1 / e\n #thus e * singleton_bins / 2160 == 1\n by_block['nonce_dist'] = (exp(1)*singleton_bins/(360*3))\n by_block['nonce'] = int(x[7])/max_nonce\n \n for i in range(len(block_output)):\n block_output[i].append(list(by_block.values())[i])\n \n # by month\n if datetime.fromtimestamp(x[0]).strftime('%B') != datetime.fromtimestamp(by_month['timestamp']).strftime('%B') or len(blocks)==0:\n if(by_month['tx']>0):\n by_month['tx_avg']=by_month['volume']/by_month['tx']\n by_month['fee']=by_month['fee']/by_month['tx']\n for i in range(len(month_output)):\n month_output[i].append(list(by_month.values())[i])\n by_month = {\n 'timestamp' : x[0],\n 'block_size' : 0,\n 'fee' : 0,\n 'fee_usd' : 0,\n 'inputs' : 0,\n 'miner_revenue' : 0,\n 'outputs' : 0,\n 'outputs_inputs' : 0,\n 'reddit_posts' : 0,\n 'reddit_comments' : 0,\n 'tx' : 0,\n 'tx_avg' : 0,\n 'volume' : 0,\n }\n else:\n by_month['timestamp'] = x[0]\n return block_output,month_output\n \n","sub_path":"charts/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"64939722","text":"\r\nimport MySQLdb, re, time\r\nfrom common_functions import *\r\nfrom parameters import *\r\n\r\nstartTime = time.time()\r\n\r\n######################################################\r\n\r\ndb = MySQLdb.connect(host=\"localhost\",\r\n user=\"root\",\r\n passwd=\"\",\r\n db=\"facebook3\")\r\n\r\ncursor = db.cursor()\r\n\r\n######################################################\r\n\r\nf = open(\"tmp/tags_relations1.txt\", 'r') # It seems that tags_relations2.txt is basically included, so not quite useful.\r\n\r\ntagsInfo = {}\r\n\r\nfor relation in f:\r\n info = re.split('[ ,()\\n]', relation)\r\n tag, relatedTag, supp, conf = info[2], info[0], float(info[4]), float(info[6])\r\n \r\n if conf >= threshold_relatedtag:\r\n if tag not in tagsInfo: \r\n cursor.execute(\"SELECT * FROM tags WHERE name = '\" + tag + \"';\")\r\n row = cursor.fetchone()\r\n tagsInfo[tag] = TagInfo(row[1], row[2], row[3], 0, set())\r\n ## If leave argument related blank (although default value is also set()),\r\n ## the relatedTags parameter of all classes will point to the same set\r\n ## in python. Therefore, it doesn't work.\r\n tagsInfo[tag].addRelatedTag(relatedTag)\r\n\r\n######################################################\r\n\r\ntagsInfoCopy = {}\r\n\r\nfor k, v in tagsInfo.items():\r\n cursor.execute(\"SELECT EXISTS (SELECT * FROM tags_use WHERE name = '\"\r\n + k\r\n + \"');\")\r\n if cursor.fetchone()[0]:\r\n cursor.execute(\"UPDATE tags_use SET relatedTags = '\"\r\n + ' '.join(v.relatedTags)\r\n + \"' WHERE name = '\"\r\n + k\r\n + \"';\")\r\n else: tagsInfoCopy[k] = v\r\n\r\n## just filter out the keys which already exist in database\r\ntagsInfo = tagsInfoCopy\r\n\r\ncursor.execute(\"SELECT title FROM sample;\")\r\ndb.commit()\r\n\r\nrenewTagsInfoIncorrect(tagsInfo, cursor)\r\n\r\nfor k, v in tagsInfo.items():\r\n if v.countYes >= threshold_newtag * (v.countYes + v.countIncorrect):\r\n cursor.execute(\"INSERT INTO tags_use VALUES ('\"\r\n + k + \"',\"\r\n + str(v.count) + \",\"\r\n + str(v.countYes) + \",\"\r\n + str(v.countNo) + \",\"\r\n + str(v.countIncorrect) + \",'\"\r\n + ' '.join(v.relatedTags) + \"');\")\r\n\r\ndb.commit()\r\n\r\ndb.close()\r\n\r\n######################################################\r\n\r\nprint(\"Executed tags_related_statistics.py - Time: \" + str(time.time()-startTime))\r\n","sub_path":"data/external/repositories_2to3/136086/kaggle-master/facebook-recruiting-iii/tags_related_statistics.py","file_name":"tags_related_statistics.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"52198595","text":"import roslib;\nimport rospy\nimport smach\nimport smach_ros\n\n# define state Task_managment:\nclass Task_managment(smach.State):\n def __init__(self):\n smach.State.__init__(self, outcomes=['set_command','success'],input_keys=['monitor_output_list_of_triple'], output_keys=['triple'])\n self.task_complete=False\n self.num_of_triple=0\n\n def execute(self, userdata):\n rospy.loginfo('Executing state Task_managment:')\n\n list_of_triples=userdata.monitor_output_list_of_triple\n\n if(self.num_of_triple==len(list_of_triples)):\n self.task_complete=True\n\n if (self.task_complete==True):\n self.reset_condition()\n return 'success'\n else:\n #userdata.task_output=userdata.task_input\n #Add;\n #logic of controling of movement to points in one task;\n if(self.num_of_triple.\n\n\nimport control\nimport board\n\ntry:\n control.go(0)\n\n for e in board.Board.circle((411, 205), 10):\n control.sierra.vaccinate(200, e)\n for e in board.Board.circle((329, 164), 10):\n control.sierra.vaccinate(200, e)\n for e in board.Board.circle((239, 274), 10):\n control.sierra.vaccinate(200, e)\n for e in board.Board.circle((236, 156), 10):\n control.sierra.vaccinate(200, e)\n\n with open('treated-%s.txt' % control.name, 'w') as f:\n f.write('%f\\n' % control.sierra.treated)\n\n for i in range(1, 4):\n control.go(i)\n\nfinally:\n control.log_history()\n","sub_path":"trialch.py","file_name":"trialch.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"403974689","text":"#!/usr/bin/python\nimport sys\nimport socket \n\ndef main():\n \"\"\"Queries an NTP server and gets the time from it\n\n \"\"\"\n if len(sys.argv) != 2:\n sys.exit(\"usage: daytimetcpcli.py \")\n\n try:\n sockfd = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n except Exception as exc:\n sys.exit(\"socket error %s\" % exc)\n\n try:\n sockfd.connect((sys.argv[1], 13))\n except Exception as exc:\n sys.exit(\"connection error %s\" % exc)\n\n \n lines = []\n while True:\n line = sockfd.recv(1024)\n if not line:\n break\n lines.append(line)\n recvline = ''.join(lines).strip()\n\n if len(recvline) > 0:\n print (recvline)\n else:\n sys.exit(\"read error\")\nif __name__ == \"__main__\":\n \n main()\n\n","sub_path":"intro/daytimetcpcliv6.py","file_name":"daytimetcpcliv6.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"482551887","text":"# 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。\n#\n# 注意:答案中不可以包含重复的三元组。\n#\n# 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],\n#\n# 满足要求的三元组集合为:\n# [\n# [-1, 0, 1],\n# [-1, -1, 2]\n# ]\n\n\nclass Solution:\n def threeSum(self, nums):\n num = sorted(nums)\n res_list = []\n lens = len(num)\n if set(nums) == {0}:\n if lens > 2:\n return [[0, 0, 0]]\n else:\n return res_list\n for i in range(lens - 2):\n if num[i] == num[i-1]:\n continue\n j = i + 1\n k = lens - 1\n add_num = -num[i]\n while j < k:\n if num[j] + num[k] == add_num:\n res_list.append([num[i], num[j], num[k]])\n j = j + 1\n while j < k and num[j] == num[j-1]:\n j = j + 1\n elif add_num > num[j] + num[k]:\n j = j + 1\n else:\n k = k - 1\n return res_list\n\n\ns = Solution()\nres = s.threeSum([0, 0, 0])\nprint(res)\n","sub_path":"15threeSum.py","file_name":"15threeSum.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"292657292","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom csv import DictWriter\nimport os\nwin = tk.Tk()\nwin.title('GUI APP')\n\n#create Lable on window\nname_lable=ttk.Label(win,text='Enter Your Name : ')\nname_lable.grid(row=0,column=0, sticky=tk.W)\n\nemail=ttk.Label(win,text='Enter Your Email : ')\nemail.grid(row=1,column=0,sticky=tk.W)\n\nage_lable=ttk.Label(win,text='Enter Your Age : ')\nage_lable.grid(row=2,column=0,sticky=tk.W)\n\nuser_lable=ttk.Label(win,text='Select your type : ')\nuser_lable.grid(row=4,column=0,sticky=tk.W)\n\ngender_lable=ttk.Label(win,text='Select Your Gender : ')\ngender_lable.grid(row=5,column=0)\n\n#defining function\ndef info():\n name=name_var.get()\n email=email_var.get()\n age=age_var.get()\n user=user_type.get()\n gender=gender_var.get()\n if check_var.get()==0:\n subscribe='NO'\n else:\n subscribe='Yes'\n with open('file.csv','a',newline='') as f:\n dict_write=DictWriter(f,fieldnames=['name','email','age','user_type','gender','subscribe'])\n if os.stat('file.csv').st_size==0:\n dict_write.writeheader()\n dict_write.writerow({\n 'name':name,\n 'email':email,\n 'age':age,\n 'user_type':user,\n 'gender':gender,\n 'subscribe':subscribe,\n })\n name_entry.delete(0,tk.END)\n age_lable.delete(0,tk.END)\n email_entry.delete(0,tk.END)\n\n#creating variables\nname_var=tk.StringVar()\nname_entry=ttk.Entry(win,width=16,textvariable=name_var)\nname_entry.grid(row=0,column=1)\nname_entry.focus()\n\n\nemail_var=tk.StringVar()\nemail_entry=ttk.Entry(win,width=16,textvariable=email_var)\nemail_entry.grid(row=1,column=1)\n\nage_var=tk.StringVar()\nage_lable=ttk.Entry(win,width=16,textvariable=age_var)\nage_lable.grid(row=2,column=1)\n\n# creating combobox\ngender_var=tk.StringVar()\nuser_gender=ttk.Combobox(win,width=14,textvariable=gender_var,state='readonly')\nuser_gender['values']=('MALE','Female','OTHER')\nuser_gender.current(0)\nuser_gender.grid(row=5,column=1)\n\n# creating radio button\nuser_type=tk.StringVar()\nradiobtn1=ttk.Radiobutton(win,text='student',value='student',variable=user_type)\nradiobtn1.grid(row=4,column=1)\nradiobtn2=ttk.Radiobutton(win,text='teacher',value='teacher',variable=user_type)\nradiobtn2.grid(row=4,column=2)\n\n# Submit button\nsubmit_button=ttk.Button(win,text='Submit', command=info)\nsubmit_button.grid(row=7,column=1)\n\n# check button\ncheck_var=tk.IntVar()\ncheckbtn1=ttk.Checkbutton(win,text='Select For Subscribe News Letter .',variable=check_var)\ncheckbtn1.grid(row=6,columnspan=3)\n\n# name_entry.focus()\nwin.mainloop()","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"33430350","text":"from odoo import models, fields, api\nfrom odoo.tools.translate import _\n\nclass product_product(models.Model):\n _inherit = 'product.product'\n\n def compute_avarage_cost(self):\n inventories = self.env['stock.quant'].search([('product_id', '=', self.id)])\n if(inventories):\n quantity = inventories.mapped('qty')\n inventory_values = inventories.mapped('inventory_value')\n if sum(quantity) == 0:\n return 0.0\n return sum(inventory_values)/float(sum(quantity))\n else:\n return 0.0\n\nclass PosOrderLine(models.Model):\n _inherit = 'pos.order.line'\n\n cost = fields.Float('Cost')\n\n @api.model\n def create(self, vals):\n pos_line = super(PosOrderLine, self).create(vals)\n def check_bom(bom, qty):\n total = 0.0\n bom_obj = self.env['mrp.bom']\n for line in bom.bom_line_ids:\n inner_bom = bom_obj.search([('product_tmpl_id', '=', line.product_id.product_tmpl_id.id)])\n if not inner_bom:\n amount = line.product_uom_id._compute_quantity(line.product_qty * qty, line.product_id.uom_id, round=True, rounding_method='UP')\n total += amount * line.product_id.compute_avarage_cost()\n else:\n qty = line.product_uom_id._compute_quantity(line.product_qty * qty, line.product_id.uom_id, round=True, rounding_method='UP')\n total += check_bom(inner_bom, qty)\n return total\n \n bom = self.env['mrp.bom'].search([('product_tmpl_id','=',pos_line.product_id.product_tmpl_id.id)])\n qty = pos_line.qty\n if bom:\n pos_line.cost = check_bom(bom, qty)\n else:\n pos_line.cost = float(qty) * float(pos_line.product_id.standard_price)\n return pos_line\n\n\n","sub_path":"beta-dev1/cogs_bom_pos/models/pos_order.py","file_name":"pos_order.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"475480050","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.forms.forms import NON_FIELD_ERRORS\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\n\nfrom .models import FormData, FormPlugin, User\nfrom .utils import add_form_error\n\n\nclass FormDataBaseForm(forms.Form):\n\n form_plugin_id = forms.IntegerField(widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs):\n self.form_plugin = kwargs.pop('form_plugin')\n super(FormDataBaseForm, self).__init__(*args, **kwargs)\n self.instance = FormData(name=self.form_plugin.name)\n self.fields['form_plugin_id'].initial = self.form_plugin.pk\n\n def _add_error(self, message, field=NON_FIELD_ERRORS):\n try:\n self._errors[field].append(message)\n except KeyError:\n self._errors[field] = self.error_class([message])\n\n def save(self):\n recipients = self.form_plugin.recipients.all()\n\n self.instance.set_form_data(self)\n self.instance.save()\n\n self.instance.people_notified.add(*recipients)\n\n self.instance.send_notification_email(form=self, form_plugin=self.form_plugin)\n\n\nclass ExtandableErrorForm(forms.ModelForm):\n\n def append_to_errors(self, field, message):\n add_form_error(form=self, message=message, field=field)\n\n\nclass FormPluginForm(ExtandableErrorForm):\n\n def __init__(self, *args, **kwargs):\n super(FormPluginForm, self).__init__(*args, **kwargs)\n if getattr(settings, 'ALDRYN_FORMS_SHOW_ALL_RECIPIENTS', False):\n self.fields['recipients'].queryset = User.objects.all()\n\n def clean(self):\n redirect_type = self.cleaned_data.get('redirect_type')\n page = self.cleaned_data.get('page')\n url = self.cleaned_data.get('url')\n\n if redirect_type:\n if redirect_type == FormPlugin.REDIRECT_TO_PAGE:\n if not page:\n self.append_to_errors('page', _('Please provide CMS page for redirect.'))\n self.cleaned_data['url'] = None\n if redirect_type == FormPlugin.REDIRECT_TO_URL:\n if not url:\n self.append_to_errors('url', _('Please provide an absolute URL for redirect.'))\n self.cleaned_data['page'] = None\n\n return self.cleaned_data\n\n\nclass BooleanFieldForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n if 'instance' not in kwargs: # creating new one\n initial = kwargs.pop('initial', {})\n initial['required'] = False\n kwargs['initial'] = initial\n super(BooleanFieldForm, self).__init__(*args, **kwargs)\n\n class Meta:\n fields = ['label', 'help_text', 'required', 'required_message', 'custom_classes']\n\n\nclass SelectFieldForm(forms.ModelForm):\n\n class Meta:\n fields = ['label', 'help_text', 'required', 'required_message', 'custom_classes']\n\n\nclass RadioFieldForm(forms.ModelForm):\n\n class Meta:\n fields = ['label', 'help_text', 'required', 'required_message', 'custom_classes']\n\n\nclass CaptchaFieldForm(forms.ModelForm):\n\n class Meta:\n # captcha is always required\n fields = ['label', 'help_text', 'required_message']\n\n\nclass MinMaxValueForm(ExtandableErrorForm):\n\n def clean(self):\n min_value = self.cleaned_data.get('min_value')\n max_value = self.cleaned_data.get('max_value')\n if min_value and max_value and min_value > max_value:\n self.append_to_errors('min_value', _(u'Min value can not be greater then max value.'))\n return self.cleaned_data\n\n\nclass TextFieldForm(MinMaxValueForm):\n\n def __init__(self, *args, **kwargs):\n super(TextFieldForm, self).__init__(*args, **kwargs)\n\n self.fields['min_value'].label = _(u'Min length')\n self.fields['min_value'].help_text = _(u'Required number of characters to type.')\n\n self.fields['max_value'].label = _(u'Max length')\n self.fields['max_value'].help_text = _(u'Maximum number of characters to type.')\n self.fields['max_value'].required = True\n\n class Meta:\n fields = ['label', 'placeholder_text', 'help_text',\n 'min_value', 'max_value', 'required', 'required_message', 'custom_classes']\n\n\nclass EmailFieldForm(TextFieldForm):\n\n def __init__(self, *args, **kwargs):\n super(EmailFieldForm, self).__init__(*args, **kwargs)\n self.fields['min_value'].required = False\n self.fields['max_value'].required = False\n\n class Meta:\n fields = [\n 'label',\n 'placeholder_text',\n 'help_text',\n 'min_value',\n 'max_value',\n 'required',\n 'required_message',\n 'email_send_notification',\n 'custom_classes'\n ]\n\n\nclass TextAreaFieldForm(TextFieldForm):\n\n def __init__(self, *args, **kwargs):\n super(TextAreaFieldForm, self).__init__(*args, **kwargs)\n self.fields['max_value'].required = False\n\n class Meta:\n fields = ['label', 'placeholder_text', 'help_text', 'text_area_columns',\n 'text_area_rows', 'min_value', 'max_value', 'required', 'required_message', 'custom_classes']\n\n\nclass MultipleSelectFieldForm(MinMaxValueForm):\n\n def __init__(self, *args, **kwargs):\n super(MultipleSelectFieldForm, self).__init__(*args, **kwargs)\n\n self.fields['min_value'].label = _(u'Min choices')\n self.fields['min_value'].help_text = _(u'Required amount of elements to chose.')\n\n self.fields['max_value'].label = _(u'Max choices')\n self.fields['max_value'].help_text = _(u'Maximum amount of elements to chose.')\n\n class Meta:\n # 'required' and 'required_message' depend on min_value field validator\n fields = ['label', 'help_text', 'min_value', 'max_value', 'custom_classes']\n","sub_path":"aldryn_forms/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"19769663","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2021, libracore and contributors\n# For license information, please see license.txt\n\nimport frappe\nfrom energielenker.energielenker.timesheet_manager import \\\n get_employee_rate_external\nfrom frappe import _\nfrom frappe.model.naming import make_autoname\nfrom frappe.utils.data import get_datetime\n\n\nclass PowerProject():\n def __init__(self, project):\n self.project = project\n self.subprojects = []\n \n for row in project.subprojects:\n pp = PowerProject(frappe.get_doc(\"Project\", row.subproject))\n pp.project.update_costing()\n pp.update_kpis()\n self.subprojects.append(pp.project)\n\n def update_kpis(self):\n self.update_erpnext_kpis()\n self.update_custom_kpis()\n self.update_dates()\n self.project.calculate_gross_margin()\n self.update_payment_schedule()\n\n def update_custom_kpis(self):\n custom_kpis = [\n \"open_quotation_amount\",\n \"expected_time\",\n \"expected_billable_amount\",\n \"open_time\",\n \"open_billable_amount\",\n \"time_trend\",\n \"billable_amount_trend\",\n \"expected_purchase_cost\",\n \"purchase_cost_trend\",\n \"overall_trend\",\n \"total_amount\"\n ]\n\n for kpi in custom_kpis:\n self.update_custom_kpi(kpi)\n\n def update_erpnext_kpis(self):\n erpnext_kpis = [\n \"actual_time\",\n \"total_costing_amount\",\n \"total_expense_claim\",\n \"total_purchase_cost\",\n \"total_sales_amount\",\n \"total_billable_amount\",\n \"total_billed_amount\",\n \"total_consumed_material_cost\"\n ]\n\n for kpi in erpnext_kpis:\n self.update_erpnext_kpi(kpi)\n\n def update_payment_schedule(self):\n if self.project.sales_order:\n sales_order = frappe.get_doc(\"Sales Order\", self.project.sales_order)\n found_so = False\n if len(self.project.payment_schedule) > 0:\n # check if SO already exist\n for ps in self.project.payment_schedule:\n if ps.order == sales_order.name:\n found_so = True\n if not found_so:\n # add SO\n for so_ps in sales_order.payment_schedule:\n new_ps = self.project.append('payment_schedule', {})\n new_ps.order = sales_order.name\n new_ps.date = so_ps.due_date\n new_ps.amount = so_ps.payment_amount\n if self.project.total_amount:\n percent_of_total_amount = so_ps.payment_amount / self.project.total_amount * 100;\n new_ps.percent = percent_of_total_amount\n \n def update_dates(self):\n dates = [\n (\"actual_start_date\", False),\n (\"actual_end_date\", True)\n ]\n\n for (date, startdate) in dates:\n self.update_date(date, startdate)\n\n def update_date(self, date, startdate):\n dates = [subproject.get(date) for subproject in self.subprojects if subproject.get(date)]\n project_date = self.project.get(date)\n\n if project_date:\n dates.append(get_datetime(project_date))\n\n if dates:\n self.project.set(date, max(dates) if startdate else min(dates))\n\n def update_custom_kpi(self, kpi):\n value_project = getattr(self, \"get_{kpi}\".format(kpi=kpi))()\n self.update_kpi(kpi, value_project)\n\n def update_erpnext_kpi(self, kpi):\n value_project = self.project.get(kpi) or 0\n self.update_kpi(kpi, value_project)\n\n def update_kpi(self, kpi, value_project):\n value_subprojects = 0\n\n for subproject in self.subprojects:\n value_subprojects += subproject.get(kpi)\n\n self.project.set(kpi, value_project + value_subprojects)\n\n def get_overall_trend(self):\n return self.get_purchase_cost_trend() + self.get_billable_amount_trend()\n\n def get_purchase_cost_trend(self):\n return self.get_expected_purchase_cost() - (self.project.total_purchase_cost or 0)\n\n def get_expected_purchase_cost(self):\n return frappe.get_all(\n \"Purchase Order Item\",\n filters={\n \"project\": self.project.name,\n \"docstatus\": [\"=\", \"1\"]\n },\n fields=[\"sum(base_net_amount) as sum\"],\n )[0].sum or 0\n\n def get_time_trend(self):\n time_trend = (self.get_expected_time() - self.project.actual_time) - self.get_open_time()\n return time_trend\n\n def get_billable_amount_trend(self):\n return (\n self.get_expected_billable_amount()\n - (self.project.total_billable_amount or 0)\n + self.get_open_billable_amount()\n )\n\n def get_open_quotation_amount(self):\n return frappe.get_all(\n \"Quotation\",\n filters={\n \"project\": self.project.name,\n \"status\": [\"in\", [\"Open\", \"Replied\"]]\n },\n fields=[\"sum(grand_total) as sum\"],\n )[0].sum or 0\n\n def get_expected_time(self):\n return frappe.get_all(\n \"Task\",\n filters={\n \"project\": self.project.name,\n \"status\": [\"not in\", [\"Cancelled\"]]\n },\n fields=[\"sum(expected_time) as sum\"]\n )[0].sum or 0\n\n def get_open_billable_amount(self):\n open_tasks = frappe.get_all(\n \"Task\",\n filters={\n \"project\": self.project.name,\n \"status\": [\"not in\", [\"Completed\", \"Cancelled\"]]\n },\n fields=[\"expected_time\", \"actual_time\", \"completed_by\"],\n )\n \n open_billable_amount = 0\n\n for task in open_tasks:\n open_billable_amount += (\n max(task.expected_time - task.actual_time, 0) \n * self.get_employee_rate(task.completed_by)\n )\n \n return open_billable_amount\n\n def get_expected_billable_amount(self):\n tasks = frappe.get_all(\n \"Task\",\n filters={\n \"project\": self.project.name\n },\n fields=[\"expected_time\", \"completed_by\"]\n )\n \n expected_billable_amount = 0\n\n for task in tasks:\n expected_billable_amount += (\n task.expected_time \n * self.get_employee_rate(task.completed_by)\n )\n \n return expected_billable_amount\n\n def get_employee_rate(self, employee):\n employee = frappe.get_value(\"Employee\", {\"user_id\": employee}, \"name\")\n\n return (\n get_employee_rate_external(employee) \n if employee\n else self.project.default_external_rate\n )\n\n def get_open_time(self):\n open_tasks = frappe.get_all(\n \"Task\",\n filters={\n \"project\": self.project.name,\n \"status\": [\"not in\", [\"Completed\", \"Cancelled\"]]\n },\n fields=[\"expected_time\", \"actual_time\"],\n as_list=True\n )\n \n return sum(map(lambda task: (task[0] - task[1]), open_tasks))\n \n def get_total_amount(self):\n return self.project.total_sales_amount\n\ndef autoname(project, event):\n project.name = make_autoname(project.naming_series)\n\ndef onload(project, event):\n #if project.sales_order and not project.payment_schedule:\n #fetch_payment_schedule(project, project.sales_order)\n PowerProject(project).update_kpis()\n\ndef validate(project, event):\n validate_subprojects(project)\n PowerProject(project).update_kpis()\n mark_subprojects_as_subproject(project)\n \ndef mark_subprojects_as_subproject(project):\n for row in project.subprojects:\n subproject = frappe.get_doc(\"Project\", row.subproject)\n if not subproject.subproject:\n subproject.subproject = 1\n subproject.save()\n\ndef validate_subprojects(project):\n for row in project.subprojects:\n if project.name == row.subproject:\n frappe.throw(_(\"Project cannot be a subproject of itself.\"))\n\n parent_project = frappe.get_value(\n \"Subproject\",\n {\"subproject\": row.subproject},\n \"parent\"\n )\n\n if parent_project and parent_project != project.name:\n frappe.throw(_(\"Subproject {} is already part of project {}.\")\n .format(row.subproject, parent_project))\n\n if subproject_is_a_parent_of_project(row.subproject, project.name):\n frappe.throw(_(\"Subproject {} is actually a parent of project {}.\")\n .format(row.subproject, project.name))\n\ndef subproject_is_a_parent_of_project(subproject, project):\n subprojects_of_subproject = get_subprojects(subproject)\n\n if not subprojects_of_subproject:\n return False\n\n if project in subprojects_of_subproject:\n return True\n\n for subproject in subprojects_of_subproject:\n if subproject_is_a_parent_of_project(subproject, project):\n return True\n\n return False\n\ndef get_subprojects(project):\n subprojects = frappe.get_all(\n \"Subproject\",\n filters={\n \"parent\": project,\n },\n fields=[\"subproject\"],\n as_list=True\n )\n\n return [subproject[0] for subproject in subprojects]\n\n@frappe.whitelist()\ndef get_contact_details(doc):\n from frappe.contacts.doctype.address.address import get_condensed_address\n\n contact = frappe.get_doc(\"Contact\", doc).as_dict()\n\n contact[\"email_ids\"] = frappe.get_list(\"Contact Email\", filters={\n \"parenttype\": \"Contact\",\n \"parent\": contact.name,\n \"is_primary\": 0\n }, fields=[\"email_id\"])\n\n contact[\"phone_nos\"] = frappe.get_list(\"Contact Phone\", filters={\n \"parenttype\": \"Contact\",\n \"parent\": contact.name,\n \"is_primary_phone\": 0,\n \"is_primary_mobile_no\": 0\n }, fields=[\"phone\"])\n\n if contact.address:\n address = frappe.get_doc(\"Address\", contact.address)\n contact[\"address\"] = get_condensed_address(address)\n\n return {\"contact_list\": [contact]}\n\n@frappe.whitelist()\ndef fetch_payment_schedule(project, sales_order, payment_schedule=False):\n if payment_schedule:\n import json\n payment_schedule = json.loads(payment_schedule)\n \n project = frappe.get_doc(\"Project\", project)\n \n if not payment_schedule:\n payment_schedule = project.payment_schedule\n \n found_so = False\n \n if len(project.payment_schedule) > 0:\n # check if SO already exist\n for ps in project.payment_schedule:\n if ps.order == sales_order:\n found_so = True\n if not found_so:\n # add SO\n for so_ps in payment_schedule:\n new_ps = project.append('payment_schedule', {})\n new_ps.order = sales_order\n new_ps.date = so_ps[\"due_date\"]\n new_ps.amount = so_ps[\"payment_amount\"]\n if project.total_amount:\n percent_of_total_amount = so_ps[\"payment_amount\"] / project.total_amount * 100;\n new_ps.percent = percent_of_total_amount\n project.save()\n \n try:\n # create assignment\n from frappe.desk.form.assign_to import add\n add(args = {\n 'assign_to': project.project_manager,\n 'doctype': 'Project',\n 'name': project.name,\n 'description': _('Check the Payment Forecast Table')\n })\n except frappe.desk.form.assign_to.DuplicateToDoError:\n frappe.local.message_log = []\n \n frappe.db.commit()\n \n return\n\n@frappe.whitelist()\ndef clear_payment_schedule(project, sales_order):\n frappe.db.sql(\"\"\"DELETE FROM `tabPayment Forecast` WHERE `parent` = '{project}' AND `order` = '{sales_order}'\"\"\".format(project=project, sales_order=sales_order), as_list=True)\n return\n","sub_path":"energielenker/energielenker/project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":12117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"43765130","text":"import logging\n\n# logging.basicConfig(level=logging.DEBUG,format=\"%(asctime)s [%(levelname)s] %(message)s\")\n\n# logging.debug(\"아 이거, 누가 짠거야~~\")\n# logging.info(\"자동화 수행 준비\")\n# logging.warning(\"이 스크립트는 조금 오래 되었습니다. 실험실에 문제가 있을 수 있습니다\")\n# logging.error(\"에러가 발생했습니다. 에러 코드는 ...\")\n# logging.critical(\"복구가 불가능한 심각한 문제가 발생했습니다...\")\n\n# logging.basicConfig(level=logging.INFO,format=\"%(asctime)s [%(levelname)s] %(message)s\")\n\n# logging.debug(\"아 이거, 누가 짠거야~~\")#안나옴\n# logging.info(\"자동화 수행 준비\")\n# logging.warning(\"이 스크립트는 조금 오래 되었습니다. 실험실에 문제가 있을 수 있습니다\")\n# logging.error(\"에러가 발생했습니다. 에러 코드는 ...\")\n# logging.critical(\"복구가 불가능한 심각한 문제가 발생했습니다...\")\n\nfrom datetime import datetime\nlogFormatter =logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nstreamHandler = logging.StreamHandler()\nstreamHandler.setFormatter(logFormatter)\nlogger.addHandler(streamHandler)\n\nfilename = datetime.now().strftime(\"mylogfile_%Y%m%d%H%M%S.log\")\nfileHandler = logging.FileHandler(filename,encoding=\"utf-8\")\nfileHandler.setFormatter(logFormatter)\nlogger.addHandler(fileHandler)\n\nlogger.debug(\"로그를 남겨보는 테스트를 진행합니다\")","sub_path":"git_test/rpa_basic/2_desktop/10_log.py","file_name":"10_log.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"395573674","text":"# -*- coding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport pickle\nimport numpy as np\nimport tempfile\nimport unittest\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.testing.connectutils import should_test_connect, connect_requirement_message\n\nif should_test_connect:\n from pyspark.ml.connect.feature import (\n MaxAbsScaler,\n MaxAbsScalerModel,\n StandardScaler,\n StandardScalerModel,\n )\n\n\nclass FeatureTestsMixin:\n def test_max_abs_scaler(self):\n df1 = self.spark.createDataFrame(\n [\n ([2.0, 3.5, 1.5],),\n ([-3.0, -0.5, -2.5],),\n ],\n schema=[\"features\"],\n )\n\n scaler = MaxAbsScaler(inputCol=\"features\", outputCol=\"scaled_features\")\n\n model = scaler.fit(df1)\n assert model.uid == scaler.uid\n result = model.transform(df1).toPandas()\n assert list(result.columns) == [\"features\", \"scaled_features\"]\n\n expected_result = [[2.0 / 3, 1.0, 0.6], [-1.0, -1.0 / 7, -1.0]]\n\n np.testing.assert_allclose(list(result.scaled_features), expected_result)\n\n local_df1 = df1.toPandas()\n local_fit_model = scaler.fit(local_df1)\n local_transform_result = local_fit_model.transform(local_df1)\n assert id(local_transform_result) == id(local_df1)\n assert list(local_transform_result.columns) == [\"features\", \"scaled_features\"]\n\n np.testing.assert_allclose(list(local_transform_result.scaled_features), expected_result)\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n estimator_path = os.path.join(tmp_dir, \"estimator\")\n scaler.saveToLocal(estimator_path)\n loaded_scaler = MaxAbsScaler.loadFromLocal(estimator_path)\n assert loaded_scaler.getInputCol() == \"features\"\n assert loaded_scaler.getOutputCol() == \"scaled_features\"\n\n model_path = os.path.join(tmp_dir, \"model\")\n model.saveToLocal(model_path)\n loaded_model = MaxAbsScalerModel.loadFromLocal(model_path)\n\n np.testing.assert_allclose(model.scale_values, loaded_model.scale_values)\n np.testing.assert_allclose(model.max_abs_values, loaded_model.max_abs_values)\n assert model.n_samples_seen == loaded_model.n_samples_seen\n\n # Test loading core model as scikit-learn model\n with open(os.path.join(model_path, \"MaxAbsScalerModel.sklearn.pkl\"), \"rb\") as f:\n sk_model = pickle.load(f)\n sk_result = sk_model.transform(np.stack(list(local_df1.features)))\n np.testing.assert_allclose(sk_result, expected_result)\n\n def test_standard_scaler(self):\n df1 = self.spark.createDataFrame(\n [\n ([2.0, 3.5, 1.5],),\n ([-3.0, -0.5, -2.5],),\n ([1.0, -1.5, 0.5],),\n ],\n schema=[\"features\"],\n )\n\n scaler = StandardScaler(inputCol=\"features\", outputCol=\"scaled_features\")\n model = scaler.fit(df1)\n assert model.uid == scaler.uid\n result = model.transform(df1).toPandas()\n assert list(result.columns) == [\"features\", \"scaled_features\"]\n\n expected_result = [\n [0.7559289460184544, 1.1338934190276817, 0.8006407690254358],\n [-1.1338934190276817, -0.3779644730092272, -1.1208970766356101],\n [0.3779644730092272, -0.7559289460184544, 0.32025630761017426],\n ]\n\n np.testing.assert_allclose(list(result.scaled_features), expected_result)\n\n local_df1 = df1.toPandas()\n local_fit_model = scaler.fit(local_df1)\n local_transform_result = local_fit_model.transform(local_df1)\n assert id(local_transform_result) == id(local_df1)\n assert list(local_transform_result.columns) == [\"features\", \"scaled_features\"]\n\n np.testing.assert_allclose(list(local_transform_result.scaled_features), expected_result)\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n estimator_path = os.path.join(tmp_dir, \"estimator\")\n scaler.saveToLocal(estimator_path)\n loaded_scaler = StandardScaler.loadFromLocal(estimator_path)\n assert loaded_scaler.getInputCol() == \"features\"\n assert loaded_scaler.getOutputCol() == \"scaled_features\"\n\n model_path = os.path.join(tmp_dir, \"model\")\n model.saveToLocal(model_path)\n loaded_model = StandardScalerModel.loadFromLocal(model_path)\n\n np.testing.assert_allclose(model.std_values, loaded_model.std_values)\n np.testing.assert_allclose(model.mean_values, loaded_model.mean_values)\n np.testing.assert_allclose(model.scale_values, loaded_model.scale_values)\n assert model.n_samples_seen == loaded_model.n_samples_seen\n\n # Test loading core model as scikit-learn model\n with open(os.path.join(model_path, \"StandardScalerModel.sklearn.pkl\"), \"rb\") as f:\n sk_model = pickle.load(f)\n sk_result = sk_model.transform(np.stack(list(local_df1.features)))\n np.testing.assert_allclose(sk_result, expected_result)\n\n\n@unittest.skipIf(not should_test_connect, connect_requirement_message)\nclass FeatureTests(FeatureTestsMixin, unittest.TestCase):\n def setUp(self) -> None:\n self.spark = SparkSession.builder.master(\"local[2]\").getOrCreate()\n\n def tearDown(self) -> None:\n self.spark.stop()\n\n\nif __name__ == \"__main__\":\n from pyspark.ml.tests.connect.test_legacy_mode_feature import * # noqa: F401,F403\n\n try:\n import xmlrunner # type: ignore[import]\n\n testRunner = xmlrunner.XMLTestRunner(output=\"target/test-reports\", verbosity=2)\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n","sub_path":"python/pyspark/ml/tests/connect/test_legacy_mode_feature.py","file_name":"test_legacy_mode_feature.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"401446180","text":"#!/usr/bin/python3\nimport sys\nimport os\nimport jinja2\n\n\ndef main(args):\n print(\"Loading options ...\")\n kv = {}\n for a in args[1:]:\n key, value = a.split(\"=\")\n kv[key] = value\n print(f\" {key}={value}\")\n\n print(\"Rendering configuration from template ...\")\n env = jinja2.Environment(loader=jinja2.FileSystemLoader(\".\"))\n templ = env.get_template(\"config.tmpl\")\n config = templ.render(kv)\n\n print(\"Writing to config file ...\")\n try:\n os.unlink(\"config\")\n except FileNotFoundError:\n pass\n with open(\"config\", \"w\") as f:\n f.write(config)\n return 0\n\n\nif __name__ == \"__main__\":\n exit(main(sys.argv))\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616405006","text":"\r\nclass Monitor():\r\n def __init__(self, manufacturer, dateCreate, dateBuy, price, typeof, size):\r\n self.manufacturer = manufacturer\r\n self.dateCreate = dateCreate\r\n self.dateBuy = dateBuy\r\n self.price = price\r\n self.typeof = typeof\r\n self.size = size\r\n\r\n def age(self):\r\n return 2020 - self.dateCreate\r\n\r\n\r\n def DisplayTheImage(self, ImageSize, size):\r\n if ImageSize == size:\r\n print(\"Зображення можна вивести без масштабування\")\r\n else:\r\n #визначити коефіцієнт масштабування\r\n size - ImageSize #?\r\n print(\"Зображення можна вивести з масштабуванням\")\r\n\r\n\r\nMonitor_1 = Monitor('Samsung', 2007, 2009, 1562, 'Проекційний', 35)\r\n\r\nprint('Вкажіть розмір зображення:')\r\nImageSize = int(input('Розмір зображення:'))\r\nsize = int(input('Розмір Монітора: '))\r\n\r\n\r\nprint('З дати виробництва пройшло {0} років'.format(Monitor_1.age()))\r\n","sub_path":"Python-labs/-10/Завдання 2.py","file_name":"Завдання 2.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"10046680","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom bs4 import BeautifulSoup\n\noptions = Options()\noptions.headless = True\nbrowser = webdriver.Chrome(\n executable_path=\"./chromedriver.exe\", options=options)\nbrowser.get(\"https://people.search.naver.com/search.naver?where=nexearch&query=%EC%95%84%EC%9D%B4%EC%9C%A0&sm=tab_etc&ie=utf8&key=PeopleService&os=159229\")\n\nbrowser.find_element_by_partial_link_text(\n '수상').click()\n\n# test = browser.find_elements_by_xpath(\n# '//li[@nocr]').find_elements_by_css_selector(\"*\").find\n# print(tag_names.text.split(\"\\n\"))\n# for tag in test:\n# print(\"==>\")\n# print(tag)\n# tag.click()\n\n# browser.find_element_by_class_name(\n# 'people_paging').find_elements_by_css_selector('*')[4].click()\n\nhtml = browser.page_source\nsoup = BeautifulSoup(html, 'html.parser')\n\n# test = browser.find_elements_by_xpath(\n# '//*[@id=\"content\"]/div/div[3]/ul/li[2]/a')\n# test[0].click()\n# time.sleep(2)\n# browser.find_element_by_partial_link_text(\n# '다음').click()\n\ndummy = []\ntry:\n\n while True:\n\n test = browser.find_element_by_class_name(\"record_wrap\").find_elements_by_xpath(\n '//*[@id=\"pagination_prize\"]/span[4]/a')\n\n test[0].click()\n\n html = browser.page_source\n soup = BeautifulSoup(html, 'html.parser')\n for i in [2, 4, 6, 8, 10]:\n tmp = {}\n result = soup.select(\n '#listUI_prize > dd:nth-child({}) > p'.format(i))\n for r in result:\n tmp['content'] = r.text.strip()\n print(r.text.strip())\n\n result1 = soup.select(\n '#listUI_prize > dt:nth-child({})'.format(i-1))\n for r in result1:\n tmp['year'] = r.text.strip()\n print(r.text.strip())\n dummy.append(tmp)\nexcept:\n print(\"end\")\n print(dummy)\n # result = soup.select('#listUI_prize > dd:nth-child(2) > p')\n # for r in result1:\n # print(r.text.strip())\n\n # result = soup.select('p')\n\n # for r in result:\n # print(r.text)\n\n # time.sleep(3)\n\n # tag_names = browser.find_element_by_class_name(\n # 'people_paging').find_elements_by_css_selector('*')\n # # print(tag_names.text.split(\"\\n\"))\n # for tag in tag_names:\n # print(tag.text.split(\"\\n\"))\n","sub_path":"his_cr.py","file_name":"his_cr.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"644295228","text":"import pickle, os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nfrom pathlib import PurePath\ncurrent_dir = os.path.realpath(__file__)\np = PurePath(current_dir)\n\ndf_results = pd.read_pickle(str(p.parents[6])+'/test/df_results.plk')\n\n#==============================CLUSTER 8=======================================\nwith open('subclusters_of_cluster_8.pickle', 'rb') as handle:\n cluster_8 = pickle.load(handle) \n \nbest_models_f1_8 = {0: []}#, 1: [], 2: [], 3: [], 4: [], 5: [], 6: []}#, 7: [], 8: [], 9: [], 10: [], 11: []}\n\nfor key in cluster_8.keys(): #0 (since 1 sub-cluster)\n \n for dataset in cluster_8[key]:\n best_models_f1_8[key].append(df_results['Best model f1'][dataset])\n\n#==============================================================================\n# f1 - BAR CHART FOR EACH SUB-CLUSTER of cluster 8\n#==============================================================================\nfor key in list(best_models_f1_8.keys()):\n plt.figure()\n plt.bar(range(len(dict(Counter(best_models_f1_8[key])))), list(dict(Counter(best_models_f1_8[key])).values()), align='center', width = 0.25)\n plt.xticks(range(len(dict(Counter(best_models_f1_8[key])))), list(dict(Counter(best_models_f1_8[key])).keys()), rotation=45, fontsize = 14)\n plt.yticks(list(np.arange(1, max(list(dict(Counter(best_models_f1_8[key])).values())) + 1)),\n list(np.arange(1, max(list(dict(Counter(best_models_f1_8[key])).values())) + 1)))\n plt.title(\"Sub-cluster {} of Cluster 8\".format(key), weight = 'bold', fontsize = 14)\n plt.ylabel(\"Counts of best-performing model\\n (F1)\", fontsize = 14)\n","sub_path":"analysis/dataset_clustering/two_level_clustering/general_clustering_standardised/second_level_clustering/F1/sub_clusters_f1_8.py","file_name":"sub_clusters_f1_8.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307022228","text":"command = ''\nis_started = False\nwhile True:\n command = input('> ').lower()\n if command == 'start':\n if is_started:\n print('Car is already started')\n else:\n is_started = True\n print('Car started...')\n elif command == 'stop':\n if not is_started:\n print('Car is already stopped')\n else:\n is_started = False\n print('Car stopped.')\n elif command == 'help':\n print('''\n start - to start the car\n stop - to stop the car\n quit - to quit\n ''')\n elif command == 'quit':\n print('Quitting program')\n break\n else:\n print(\"Please refer to help for the proper commands\")","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"88894351","text":"#Abby\n#Module6 P2\n\n#defining test range\ndef test_range(n):\n if n in range(1,10):\n print(\"n is in the range\",(n))\n if n not in range(1,10):\n print(\"n is not in the range\",(n))\n\n#stating the number is 7 \ntest_range(7)\n","sub_path":"M6P2AC.py","file_name":"M6P2AC.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"539272833","text":"#!/usr/bin/env python\n########################################################################\n##\n## Copyright 2015 PMC-Sierra, Inc.\n##\n## Licensed under the Apache License, Version 2.0 (the \"License\"); you\n## may not use this file except in compliance with the License. You may\n## obtain a copy of the License at\n## http://www.apache.org/licenses/LICENSE-2.0 Unless required by\n## applicable law or agreed to in writing, software distributed under the\n## License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n## CONDITIONS OF ANY KIND, either express or implied. See the License for\n## the specific language governing permissions and limitations under the\n## License.\n##\n########################################################################\n\n########################################################################\n##\n## Description:\n## A post-processor for the f2fs scripting stuff.\n##\n########################################################################\n\nimport re\n\ndef fibmap(options):\n \"\"\"A post-processing file for the fibmap output.\"\"\"\n\n fibmap = []\n fFile = open(options.fibmap,'r')\n for line in fFile:\n if re.match(\"^filesystem\", line.strip()):\n bs = map(int, re.findall(\"[-+]?\\d+[\\.]?\\d*\", line))[0]\n lba = map(int, re.findall(\"[-+]?\\d+[\\.]?\\d*\", line))[2]\n if re.match(\"^[0-9]\", line.strip()):\n fibmap.append(map(int, re.findall(\"[-+]?\\d+[\\.]?\\d*\", line)))\n\n fibmap2 = []\n for this in fibmap:\n fibmap2.append([this[0], this[1]])\n fibmap2.append([this[0]+(this[3]-1)*lba, this[2]])\n\n fFileOut = open(options.fibmap+'.out','w')\n for this in fibmap2:\n fFileOut.write (\"%d %d\\n\" % (this[0], this[1]))\n\nif __name__==\"__main__\":\n import sys\n import optparse\n\n parser = optparse.OptionParser()\n parser.add_option(\"-f\", \"--fibmap\", action=\"store\", type=str,\n default=None, help=\"the fibmap file\")\n parser.add_option(\"-b\", \"--blktrace\", action=\"store\", type=str,\n default=None, help=\"the blktrace file\")\n options, args = parser.parse_args()\n\n if (not options.fibmap) or (not options.blktrace):\n raise ValueError('must specify both fibmap and blktrace files')\n\n fibmap(options)\n","sub_path":"misc/f2fs-test.py","file_name":"f2fs-test.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"311618407","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2012-2013 Clione Software\n# Authors: Oscar Carballal Prego \n# License: BSD Simplified (2-Clause BSD). See LICENSE for details.\n#\n# This file is part of Supervise project.\n\nimport settings\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n # Home page\n url(r'^$', 'core.views.home.home' , name='home'),\n\n # Administration\n url(r'^admin/', include(admin.site.urls)),\n\n # User accounts URLs\n url(r'^u/$', include('apps.thirdparty.userena.urls')),\n\n # Work groups\n url(r'^g/$', include('apps.supervise.workgroups.urls')),\n\n # Projects URLs\n url(r'^p/$', include('apps.supervise.projects.urls')),\n\n # Static pages URLs\n #url(r'^s/$', include('apps.supervise.pages.urls')),\n\n)\n\nif settings.DEBUG:\n # Serve static files\n urlpatterns += staticfiles_urlpatterns()\n # Serve uploaded files\n urlpatterns += patterns('',\n url(r'^uploads/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"src/supervise/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"254813062","text":"\"\"\"\r\nInput: square board N x N describing Aladdin's and Jafar's pawns\r\nOutput: maximum number of pawns owned by Aladdin that Jafar can beat in his turn\r\n\r\nJafar's pawn is described by the 'O' character\r\nAladdin's pawn is described by the 'X' character\r\nEmpty fields are filled with '.'\r\n\r\nBoard is described from top to bottom and from left to right.\r\n\r\nAssume N is integer within [1, 30]\r\nBoard contains exactly one pawn owned by Jafar\r\n\r\nIn checkers, you can defeat your opponents pawn by leaping over their pawn in the up-right or up-left diagonal\r\ndirections only if the target square is free. You can defeat multiple pawns, one after another, as long as your target\r\nsquares are free.\r\n\r\nExample\r\nInput:\r\nB[0] = \"..X...\"\r\nB[1] = \"......\"\r\nB[2] = \"....X.\"\r\nB[3] = \".X....\"\r\nB[4] = \"..X.X.\"\r\nB[5] = \"...O..\"\r\nOutput: 2\r\nExplanation: Jafar can go top-right and then top-left to end up in B[1][3]\r\n\r\nInput:\r\nB[0] = \"X.....\"\r\nB[1] = \".X....\"\r\nB[2] = \"..O...\"\r\nB[3] = \"....X.\"\r\nB[4] = \"......\"\r\nOutput: 0\r\n\r\nIdeas\r\n- is this similar to the 'how many paths are there in a grid' problem? in that I need to solve it recursively?\r\n- dfs?\r\n- jumps from B[5][3] tp B[3][5] to B[1][5]\r\n - first index can only decrease by 2, second index can increase or decrease by 2 from any spot\r\n - keep track of current position\r\n - if next position (2 up and 2 to either the left or right) is a '.' and position 1 up and 1 to either the left or\r\n right is an 'X', then increase the count\r\n\r\nDynamic programming\r\n- Runtime: O(n^2), Space complexity: O(n^2)\r\n\r\n- Subproblem: B[i][j] is the number of pawns jafar can own at the end of his turn after landing in position i, j\r\n\r\n- Base case: initialize all to zero?\r\n\r\n- Recurrence relation:\r\n B[i][j] = max { B[i + 2][j - 2] + 1 if B[i + 1][j - 1] == \"X\", B[i + 2][j + 2] + 1 if B[i + 1][j + 1] == \"X\"}\r\n if B[i][j] == \".\" and i + 2, j - 2, j + 2 are valid\r\n\r\n- you'd need to check for \"O\" at every iteration as well?\r\n - you check if B[i + 2][j - 2] or B[i + 2][j + 2] == \"O\" every time you try to calculate B[i][j]\r\n - after checking, you'd change B[i][j] to \"O\" if it's a free spot that gives you a point so the next iteration\r\n works?\r\n\r\nFinal answer: keep track of the running max?\r\n\"\"\"\r\n\r\n\r\ndef checkers_game(B):\r\n \"\"\"\r\n Recursive Solution\r\n Runtime: exponential, Space complexity? recursion stack?\r\n \"\"\"\r\n def get_count(player, direction):\r\n \"\"\"\r\n :param player: jafar's initial position\r\n :param direction: -1 indicates going left, 1 indicates going right\r\n :return: number of opponent pawns the player can own\r\n \"\"\"\r\n i, j = player\r\n target_i = i - 2\r\n target_j = j + direction * 2\r\n if 0 <= target_i <= n - 1 and 0 <= target_j <= n - 1:\r\n if B[i - 1][j + direction] == \"X\" and B[target_i][target_j] == \".\":\r\n return get_count((target_i, target_j), -1) + get_count((target_i, target_j), 1) + 1\r\n return 0\r\n\r\n n = len(B)\r\n # determine Jafar's position\r\n jafar = (-1, -1)\r\n for i in range(n):\r\n for j in range(n):\r\n if B[i][j] == \"O\":\r\n jafar = (i, j)\r\n break\r\n\r\n return max(get_count(jafar, -1), get_count(jafar, 1))\r\n\r\n\r\ndef checkers_game_dp(B):\r\n \"\"\"\r\n Dynamic Programming solution\r\n Runtime: O(n^2), Space complexity: O(n^2)\r\n \"\"\"\r\n def get_count(player, direction):\r\n \"\"\"\r\n :param player: jafar's final position\r\n :param direction: -1 indicates coming from the left, 1 indicates coming from the right\r\n :return: number of opponent pawns the player can own by the time player reaches final position\r\n \"\"\"\r\n i, j = player\r\n prev_i = i + 2\r\n prev_j = j + direction * 2\r\n if 0 <= prev_i <= n - 1 and 0 <= prev_j <= n - 1:\r\n if board[i + 1][j + direction] == \"X\" and board[prev_i][prev_j] == \"O\":\r\n board[i][j] = \"O\"\r\n return P[prev_i][prev_j] + 1\r\n return 0\r\n\r\n # convert B into a list of lists where each element is a list representing that row of the checker board\r\n n = len(B)\r\n board = [list(B[i]) for i in range(n)]\r\n\r\n P = []\r\n for _ in range(n):\r\n P.append([0 for _ in range(n)])\r\n\r\n max_count = 0\r\n # any final position with non-zero points cannot be in the last two rows so i starts at (n - 1) - 2\r\n for i in range(n - 3, -1, -1):\r\n for j in range(n):\r\n if board[i][j] == \".\":\r\n P[i][j] = max(get_count((i, j), -1), get_count((i, j), 1))\r\n max_count = max(max_count, P[i][j])\r\n return max_count\r\n\r\n\r\nB0 = \"..X...\"\r\nB1 = \"......\"\r\nB2 = \"....X.\"\r\nB3 = \".X....\"\r\nB4 = \"..X.X.\"\r\nB5 = \"...O..\"\r\n\r\nB = [B0, B1, B2, B3, B4, B5]\r\nassert checkers_game(B) == 2\r\nassert checkers_game_dp(B) == 2\r\n\r\nB0 = \"X.....\"\r\nB1 = \".X....\"\r\nB2 = \"..O...\"\r\nB3 = \"....X.\"\r\nB4 = \"......\"\r\nB = [B0, B1, B2, B3, B4]\r\nassert checkers_game(B) == 0\r\nassert checkers_game_dp(B) == 0\r\n\r\nB0 = \"X.....\"\r\nB1 = \".X.X..\"\r\nB2 = \"..O...\"\r\nB3 = \"....X.\"\r\nB4 = \"......\"\r\nB = [B0, B1, B2, B3, B4]\r\nassert checkers_game(B) == 1\r\nassert checkers_game_dp(B) == 1\r\n","sub_path":"microsoft/aladdin_checkers_game.py","file_name":"aladdin_checkers_game.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"229968880","text":"from collections import defaultdict\nf = open(\"popularity_sd_all.txt\", \"r\")\n#f = open(\"pop_sd_0.txt\", \"r\")\n#f = open(\"popularity_sd_pop.txt\", \"r\")\nl = f.readline()\nTB = 1000000000\na = defaultdict(lambda: defaultdict(float))\nfor l in f:\n l = l.strip().split(\" \")\n k1 = int(l[0])\n k2 = int(float(l[1])/TB)\n a[k1][k2] += float(l[2])\n\n#ps = [128, 256, 328]\n#ps = [2, 3 ,4, 100, 101, 102, 103, 201, 271287,2048,1812, 46765, 35110, 19856,310,951, 1083,2001, 2010, 3000, 4001, 512, 851, 903]\nps = [270]\n#ps = [310]\n#print(a[310])\nfor p in ps:\n vals = list(a[p].keys())\n vals.sort()\n sum_prs = 0\n prs = []\n for v in vals:\n prs.append(a[p][v])\n sum_prs += a[p][v]\n\n print(sum_prs)\n prs = [pr/sum_prs for pr in prs]\n for i in range(len(prs)):\n print(p, prs[i], vals[i])\n\n \n \n\n\n","sub_path":"final_code/results/v/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"195503269","text":"def main():\n # Get two numbers\n num1 = int(input('Enter a number: '))\n num2 = int(input('Enter another number: '))\n # If num2 is not 0, divide num1 by num2 and display the result\n if num2 != 0:\n result = num1 / num2\n print(num1, 'divided by', num2, 'is', result)\n else:\n print('Cannot divide by zero.')\n#main()\n\ndef main2():\n try:\n # Get the number of hours worked\n hours = float(input('How many hours did you work? '))\n # Get the hourly rate\n pay_rate = float(input('Enter your hourly pay rate: '))\n # Calculate the gross pay\n gross_pay = hours * pay_rate\n #Display the gross play\n print('Gross pay: £', format(gross_pay, ',.2f'), sep='')\n except ValueError:\n print('ERROR: Hours worked and hourly pay rate must be valid integers.')\n\n#main2()\n\n\ndef main3():\n # initialize an accumulator\n total = 0.0\n try:\n # Open the sales_data.txt file\n infile = open('sales.txt', 'r')\n # Read the values from the file and accumulate them\n for line in infile:\n amount = float(line)\n total += amount\n #Close the file\n infile.close()\n #print total\n print(format(total, ',.2f'))\n # function will find the first number then the file will close,\n # returning a blank space which triggers the no n numeric error\n # this error has been done on purpose\n except IOError:\n print('An error occured trying to read the file')\n except ValueError:\n print('Non-numeric data found in the file')\n except ValueError as err:\n print(err)\nmain3()","sub_path":"bootcamp/Day4/Exception Handling.py","file_name":"Exception Handling.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"195292017","text":"# coding:utf-8\n\"\"\"\ncreate on May 8, 2020 By Wayne YU\n\nFunction:\n\n统计全球各主要国家从1998-2019,国家全部互联关系的变化趋势(分为转接互联(Transit)和对等互联(Peer))\n统计网络排名前25名的国家(按AS号码分配量的排名)\n\n美国、巴西、俄罗斯、德国、英国、\n澳大利亚、波兰、印度、乌克兰、加拿大、\n法国、印度尼西亚、中国、荷兰、罗马尼亚\n意大利、西班牙、阿根廷、中国香港、孟加拉国\n\n瑞士、韩国、日本、瑞典、保加利亚、\n捷克、土耳其、伊朗、奥地利、新西兰、\n南非、新加坡、泰国、墨西哥、菲律宾、\n丹麦、挪威、芬兰、比利时、越南、\n\ncountry = [\"US\", \"BR\", \"RU\", \"DE\", \"GB\", \"AU\", \"PL\", \"IN\", \"UA\", \"CA\",\n \"FR\", \"ID\", \"CN\", \"NL\", \"RO\", \"IT\", \"ES\", \"AR\", \"HK\", \"BD\", \"CH\", \"KR\", \"JP\", \"SE\", \"BG\"]\n\n\"\"\"\nimport time\nimport csv\nimport os\n\n\ndef write_to_csv(res_list, des_path):\n \"\"\"\n 把给定的List,写到指定路径的文件中\n :param res_list:\n :param des_path:\n :return: None\n \"\"\"\n print(\"write file <%s> ...\" % des_path)\n csvFile = open(des_path, 'w', newline='', encoding='utf-8')\n try:\n writer = csv.writer(csvFile, delimiter=\"|\")\n for i in res_list:\n writer.writerow(i)\n except Exception as e:\n print(e)\n finally:\n csvFile.close()\n print(\"write finish!\")\n\n\ndef gain_as2country(as_info_file):\n \"\"\"\n 根据传入的as info file信息获取AS与国家的对应字典\n :param as_info_file:\n :return as2country:\n \"\"\"\n as2country = {} # 存储as号到country的映射关系\n file_read = open(as_info_file, 'r', encoding='utf-8')\n for line in file_read.readlines():\n line = line.strip().split(\"\\t\")\n # print(line)\n as_number = line[0]\n as_country = line[1].strip().split(\",\")[-1].strip()\n as2country[as_number] = as_country\n\n return as2country\n\n\ndef external_as_analysis(country, as2country):\n \"\"\"\n 根据输入的国家,统计该国家的出口AS数量及其互联方向的统计分析\n :param country:\n :param as2country:\n :return:\n \"\"\"\n print(country)\n # 获取1998-2020年间全球BGP互联关系的存储文件\n file_path = []\n for root, dirs, files in os.walk(\"..\\\\000LocalData\\\\as_relationships\\\\serial-1\"):\n for file_item in files:\n file_path.append(os.path.join(root, file_item))\n\n return_list = []\n temp_list = []\n for path_item in file_path:\n print(path_item)\n # 遍历一次文件,获取该国AS参与互联的关系,并对,Transit和Peer关系进行分类,包含国内、国外\n file_read = open(path_item, 'r', encoding='utf-8')\n all_cnt = 0 # 存储该国AS所有的互联关系\n peer_cnt = 0 # 存储该国AS所有互联关系中对等互联的数量\n transit_cnt = 0 # 存储该国AS所有互联关系中转接互联的数量\n for line in file_read.readlines():\n if line.strip().find(\"#\") == 0:\n continue\n try:\n as0_country = as2country[str(line.strip().split('|')[0])]\n as1_country = as2country[str(line.strip().split('|')[1])]\n if (as0_country == country) or (as1_country == country):\n all_cnt += 1\n if str(line.strip().split('|')[2]) == \"0\":\n peer_cnt += 1\n else:\n transit_cnt += 1\n except Exception as e:\n # print(e)\n pass\n\n print(\"ALL REL|PEER|TRANSIT:\", all_cnt, peer_cnt, transit_cnt)\n temp_str = path_item.split('\\\\')[-1]\n date_str = temp_str.split('.')[0]\n temp_list.append(date_str)\n temp_list.append(all_cnt)\n temp_list.append(peer_cnt)\n temp_list.append(transit_cnt)\n print(temp_list)\n return_list.append(temp_list)\n temp_list = []\n save_path = \"../000LocalData/caict_display/All_BGP_Rel_\" + country + \".csv\"\n write_to_csv(return_list, save_path)\n\n\nif __name__ == \"__main__\":\n time_start = time.time() # 记录启动时间\n # country = [\"US\", \"BR\", \"RU\", \"DE\", \"GB\", \"AU\", \"PL\", \"IN\", \"UA\", \"CA\",\n # \"FR\", \"ID\", \"CN\", \"NL\", \"RO\", \"IT\", \"ES\", \"AR\", \"HK\", \"BD\", \"CH\", \"KR\", \"JP\", \"SE\", \"BG\"]\n country = [\"US\", \"DE\", \"JP\", \"KR\", \"BR\", \"IN\", \"RU\", \"ZA\", \"SG\", \"MY\", \"ID\", \"VN\"]\n as_info_file_in = '..\\\\000LocalData\\\\as_Gao\\\\asn_info.txt'\n as2country_dict = gain_as2country(as_info_file_in)\n for country_item in country:\n external_as_analysis(country_item, as2country_dict)\n time_end = time.time()\n print(\"=>Scripts Finish, Time Consuming:\", (time_end - time_start), \"S\")\n","sub_path":"031CAICT-Display/5_all_as_rel.py","file_name":"5_all_as_rel.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"116905474","text":"from argparse import Namespace \nfrom typing import Union, Iterable, Callable, Any\n\nclass myNamespace(Namespace):\n classname: str = \"myNamespace\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n keys = lambda self: self.__dict__.keys()\n values = lambda self: self.__dict__.values()\n items = lambda self: self.__dict__.items()\n __iter__ = lambda self: iter(self.__dict__.items())\n \n def __add__(self, other) -> Namespace:\n if type(other) in [type(Namespace()), type(myNamespace())]:\n return myNamespace(**{**self.__dict__, **other.__dict__})\n elif type(other) in [type({})]:\n return myNamespace(**{**self.__dict__, **other})\n else:\n raise Exception('myNamespace can only add up to Dictionary, Namespace or myNamespace')\n \n def __getitem__(self, item):\n return ord(item)\n \n def __setitem__(self, name, value):\n self.__dict__[name] = value\n \n def __repr__(self):\n repr = [f\"{self.classname}(\"]\n for k,v in self.__dict__.items():\n repr.append(f\" {k} = {v}\")\n repr.append(\")\")\n return '\\n'.join(repr)\n \n \n \nclass FunnelMap:\n def __init__(self, keys, values):\n self.items = [*zip(keys, values)]\n \n def __getitem__(self, item):\n for k,v in self.items:\n try:\n k.__iter__\n if item in k:\n return v\n except:\n if item == k:\n return v\n \n def __setitem__(self, key, value):\n self.items.append(tuple([key, value]))\n \n def getall(self, item):\n result = []\n for k,v in self.items:\n try:\n k.__iter__\n if item in k:\n result.append(v)\n except:\n if item == k:\n result.append(v)\n return result\n \n def __dict__(self):\n _items = self.items\n try:\n return dict(_items)\n except:\n for i in rng(_items):\n try:\n hash(_items[i][0])\n except:\n _items[i] = (tuple(_items[i][0]), _items[i][1])\n return dict(_items)\n \n def __repr__(self):\n string = 'FunnelMap(\\n'\n for k,v in self.items:\n string += f' {k} = {v}\\n'\n string += ')\\n'\n return string\n \n def __iter__(self):\n return iter(self.items)\n\n \n \ndef rng(start: Union[int, Iterable] = 0, stop: Union[None, int] = None, step: int = 1) -> Iterable:\n try:\n start.__iter__\n start: int = len(list(start)) - 1\n except:\n pass\n \n if stop == None:\n stop: int = start\n start: int = 0\n \n if step < 1: raise Exception('Step must be greater than 0.')\n mx: int = max(start,stop)\n mn: int = min(start,stop)\n if mx == start:\n step: int = -step\n condition: Callable[[int], bool] = lambda start: (start < start + step <= stop) or (start > start + step >= stop)\n while condition(start):\n yield start\n start: int = start + step\n yield start\n \n \n \ndef replace(string: str, this: Any, tothis: str = '') -> str:\n '''Replace one or multiple characters in the string.'''\n def fromstr(string, S):\n return string.replace(S, tothis)\n \n def fromarray(string, A):\n for i in rng(A):\n string = string.replace(A[i], tothis)\n return string\n \n def fromdict(string, D):\n for k,v in D.items():\n string = string.replace(k, v)\n return string\n \n method = FunnelMap(keys=[str, (list, tuple, set), dict], values=[fromstr, fromarray, fromdict])\n return method[type(this)](string, this)\n \n \ndef load_data(fname):\n\twith open(fname, 'r', encoding='utf-8') as f:\n\t\treturn f.read()\n","sub_path":"app/mylib.py","file_name":"mylib.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"57549097","text":"from peutil import *\nmaxcoeff = 1000\n\ndef quad(n,a,b):\n return n**2 + a*n + b\n\nblist = [x for x in range(2,maxcoeff) if isprime(x)]\nalist = [x for x in range(-maxcoeff+1,maxcoeff) if x%2==1]\n\nmaxlen = 0\nmaxcoeffs = 1,1\nfor a in alist:\n for b in blist:\n n=0\n while isprime(quad(n,a,b)):\n n=n+1\n if n>maxlen:\n maxlen=n\n maxcoeffs = a,b\n print('New max =',n,a,b)\n\nprint(maxlen,maxcoeffs,prod(maxcoeffs))\n","sub_path":"p27.py","file_name":"p27.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"476186249","text":"__author__ = 'Joe Linn'\n\nimport unittest\nfrom tests.base import Base\nimport pylastica\n\n\nclass GeohashCellTest(unittest.TestCase, Base):\n def test_to_dict(self):\n geohash_cell_filter = pylastica.filter.GeohashCell('pin', {'lat': 37.789018, 'lon': -122.391506}, '50m')\n expected = {\n 'geohash_cell': {\n 'pin': {\n 'lat': 37.789018,\n 'lon': -122.391506\n },\n 'precision': '50m',\n 'neighbors': False\n }\n }\n self.assertEqual(geohash_cell_filter.to_dict(), expected)\n\n def test_filter(self):\n index = self._create_index('geohash_filter_test')\n doc_type = index.get_doc_type('test')\n mapping = pylastica.doc_type.Mapping(doc_type, {\n 'pin': {\n 'type': 'geo_point',\n 'geohash': True,\n 'geohash_prefix': True\n }\n })\n doc_type.mapping = mapping\n\n doc_type.add_document(pylastica.Document(1, {'pin': '9q8yyzm0zpw8'}))\n doc_type.add_document(pylastica.Document(2, {'pin': '9mudgb0yued0'}))\n index.refresh()\n\n geohash_cell_filter = pylastica.filter.GeohashCell('pin', {'lat': 32.828326, 'lon': -117.255854})\n query = pylastica.query.Query().set_filter(geohash_cell_filter)\n results = doc_type.search(query)\n\n self.assertEqual(1, len(results.results))\n\n geohash_cell_filter = pylastica.filter.GeohashCell('pin', '9', 1)\n query = pylastica.query.Query().set_filter(geohash_cell_filter)\n results = doc_type.search(query)\n\n self.assertEqual(2, len(results.results))\n\n index.delete()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/filter/test_geohashcell.py","file_name":"test_geohashcell.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307601243","text":"# Research about Randint and how to avoid case-sensitive cases\n# import random\nfrom random import randint\nprint(\"Welcome to RPS advanced game\")\nplayer_win = 0\npc_win = 0\nplayer1_choice = \"\"\nwhile player_win < 2 and pc_win < 2:\n # print(\"Player score: {} and Computer score: {}\".format(player_win, pc_win))\n for time in range(3):\n rand_number = randint(0, 2)\n if rand_number == 0:\n computer_choice = \"scissor\"\n elif rand_number == 1:\n computer_choice = \"paper\"\n else:\n computer_choice = \"rock\"\n print(\"Player score: {} and Computer score: {}\".format(player_win, pc_win))\n if player1_choice == \"quit\" or player1_choice == \"q\":\n break\n player1_choice = input(\"Player 1 chooses: \").lower() # Player intput\n if player1_choice: # if player1_choice is valid\n print(\"Computer plays {}\".format(computer_choice))\n # print(\"Computer plays: \" + computer_choice)\n if player1_choice == computer_choice: # When the choices are similar\n print(\"It is a tie\")\n elif player1_choice == \"scissor\":\n if rand_number == 1: # Paper\n print(\"Human Player wins\")\n player_win += 1\n elif rand_number == 2: # Rock\n print(\"Computer wins\")\n pc_win += 1\n elif player1_choice == \"paper\":\n if rand_number == 0: # Scissor\n print(\"Computer wins\")\n pc_win += 1\n elif rand_number == 2: # Rock\n print(\"Human Player wins\")\n player_win += 1\n elif player1_choice == \"rock\":\n if rand_number == 0: # scissor\n print(\"Human Player wins\")\n player_win += 1\n elif rand_number == 1: # Paper\n print(\"Computer wins\")\n pc_win += 1\n else:\n print(\"Human Player please enter a valid choice\")\n\nif player_win > pc_win:\n print(\"Congratulation, you won!\")\nelif player_win == pc_win:\n print(\"The result is tie!\")\nelse:\n print(\"The computer achieve Victory!\")\nprint(\"FINAL SCORE -- Player score: {} and Computer score: {}\".format(player_win, pc_win))\n","sub_path":"RPS_game/rock_paper_scissor_V3.py","file_name":"rock_paper_scissor_V3.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"510907977","text":"# Copyright 2018 Cristian Mattarei\n#\n# Licensed under the modified BSD (3-clause BSD) License.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\nimport random\n\nfrom six.moves import cStringIO\n\nfrom pysmt.printers import HRPrinter\nfrom pysmt.walkers import TreeWalker\nfrom pysmt.utils import quote\nfrom pysmt.shortcuts import Symbol, simplify, TRUE, FALSE, BOOL, And\nfrom pysmt.rewritings import conjunctive_partition\n\nfrom cosa.representation import TS\nfrom cosa.encoders.coreir import SEP\nfrom cosa.utils.generic import dec_to_bin, dec_to_hex\nfrom cosa.encoders.ltl import has_ltl_operators, HRLTLPrinter\nfrom cosa.utils.formula_mngm import get_free_variables\n\nNL = \"\\n\"\nVCD_SEP = \"-\"\n\n# Variables starting with HIDDEN are not printed\nHIDDEN = \"_-_\"\n\nclass NotRegisteredPrinterException(Exception):\n pass\n\nclass PrinterType(object):\n NONE = 0\n\n c_size = 10\n ####################\n\n SMV = 11\n STS = 12\n\n TRANSSYS = 20\n\n ####################\n\nclass PrintersFactory(object):\n printers = []\n default_printer = None\n\n # Additional printers should be registered here #\n @staticmethod\n def init_printers():\n PrintersFactory.register_printer(SMVHTSPrinter(), True)\n PrintersFactory.register_printer(STSHTSPrinter(), False)\n\n @staticmethod\n def get_default():\n return PrintersFactory.default_printer\n\n @staticmethod\n def register_printer(printer, default=False):\n if printer.get_name() not in dict(PrintersFactory.printers):\n PrintersFactory.printers.append((printer.get_name(), printer))\n if default:\n PrintersFactory.default_printer = printer\n\n @staticmethod\n def printer_by_name(name):\n PrintersFactory.init_printers()\n dprint = dict(PrintersFactory.printers)\n if name not in dprint:\n Logger.error(\"Printer \\\"%s\\\" is not registered\"%name)\n return dprint[name]\n\n @staticmethod\n def get_printers():\n PrintersFactory.init_printers()\n return [x[0] for x in PrintersFactory.printers]\n\n @staticmethod\n def get_printers_by_type(printertype):\n PrintersFactory.init_printers()\n if (printertype % PrinterType.c_size) == 0:\n return [x[1] for x in PrintersFactory.printers \\\n if (x[1].TYPE < printertype) and (x[1].TYPE >= printertype-PrinterType.c_size)]\n\n return [x[1] for x in PrintersFactory.printers if x[1].TYPE == printertype]\n\nclass HTSPrinter(object):\n name = \"PRINTER\"\n description = \"MISSING DESCRIPTION!\"\n TYPE = PrinterType.NONE\n EXT = \".none\"\n\n def __init__(self):\n self.stream = cStringIO()\n\n def print_hts(self, hts):\n pass\n\n def get_name(self):\n return self.name\n\n def get_desc(self):\n return self.description\n\nclass SMVHTSPrinter(HTSPrinter):\n name = \"SMV\"\n description = \"\\tSMV format\"\n TYPE = PrinterType.SMV\n EXT = \".smv\"\n\n def __init__(self):\n HTSPrinter.__init__(self)\n self.write = self.stream.write\n\n printer = SMVPrinter(self.stream)\n self.printer = printer.printer\n\n def print_hts(self, hts, properties=None):\n self.write(\"MODULE main\\n\")\n\n if properties is not None:\n for strprop, prop, _ in properties:\n if has_ltl_operators(prop):\n self.write(\"\\nLTLSPEC \")\n else:\n self.write(\"\\nINVARSPEC \")\n self.printer(prop)\n self.write(\";\\n\")\n\n if hts.assumptions is not None:\n self.write(\"\\n-- ASSUMPTIONS\\n\")\n for assmp in hts.assumptions:\n self.write(\"INVAR \")\n self.printer(assmp)\n self.write(\";\\n\")\n\n printed_vars = set([])\n for ts in hts.tss:\n printed_vars = self.__print_single_hts(ts, printed_vars)\n\n ret = self.stream.getvalue()\n self.stream.truncate(0)\n self.stream.seek(0)\n return ret\n\n def names(self, name):\n return \"\\\"%s\\\"\"%name\n\n def __print_single_hts(self, hts, printed_vars):\n\n has_comment = len(hts.comment) > 0\n \n if has_comment:\n lenstr = len(hts.comment)+3\n\n self.write(\"\\n%s\\n\"%(\"-\"*lenstr))\n self.write(\"-- %s\\n\"%hts.comment)\n self.write(\"%s\\n\"%(\"-\"*lenstr))\n\n locvars = [v for v in hts.vars if v not in printed_vars]\n\n for v in hts.vars:\n printed_vars.add(v)\n\n if locvars: self.write(\"\\nVAR\\n\")\n for var in locvars:\n sname = self.names(var.symbol_name())\n if var.symbol_type() == BOOL:\n self.write(\"%s : boolean;\\n\"%(sname))\n else:\n self.write(\"%s : word[%s];\\n\"%(sname, var.symbol_type().width))\n\n sections = [((hts.init),\"INIT\"), ((hts.invar),\"INVAR\"), ((hts.trans),\"TRANS\")]\n\n for (formula, keyword) in sections:\n if formula not in [TRUE(), FALSE()]:\n self.write(\"\\n%s\\n\"%keyword)\n cp = list(conjunctive_partition(formula))\n for i in range(len(cp)):\n f = simplify(cp[i])\n self.printer(f)\n if i < len(cp)-1:\n self.write(\" &\\n\")\n self.write(\";\\n\")\n\n if has_comment:\n self.write(\"\\n%s\\n\"%(\"-\"*lenstr))\n\n return printed_vars\n\nclass STSHTSPrinter(HTSPrinter):\n name = \"STS\"\n description = \"\\tSimple STS format\"\n TYPE = PrinterType.STS\n EXT = \".ssts\"\n\n simplify = False\n\n def __init__(self):\n HTSPrinter.__init__(self)\n self.write = self.stream.write\n self.simplify = False\n\n printer = STSPrinter(self.stream)\n self.printer = printer.printer\n\n def print_hts(self, hts, properties=None):\n if hts.assumptions is not None:\n self.write(\"\\n# ASSUMPTIONS\\n\")\n for assmp in hts.assumptions:\n self.write(\"INVAR \")\n self.printer(assmp)\n self.write(\";\\n\")\n\n self.__print_single_ts(hts.get_TS())\n\n ret = self.stream.getvalue()\n self.stream.truncate(0)\n self.stream.seek(0)\n return ret\n\n def names(self, name):\n return \"'%s'\"%name\n\n def _simplify_cp(self, cp):\n random.shuffle(cp)\n newcp = []\n last = False\n step = 3\n for i in range(0, len(cp)-(step-1), step):\n if i == len(cp)-step:\n last = True\n formula = simplify(And([cp[i+j] for j in range(step)]))\n newcp += list(conjunctive_partition(formula))\n\n if not last:\n for i in range(-1, -step, -1):\n newcp.append(cp[i])\n return newcp\n \n def __print_single_ts(self, ts):\n\n has_comment = len(ts.comment) > 0\n \n if has_comment:\n lenstr = len(ts.comment)+3\n\n self.write(\"\\n%s\\n\"%(\"-\"*lenstr))\n self.write(\"# %s\\n\"%ts.comment)\n self.write(\"%s\\n\"%(\"-\"*lenstr))\n\n sections = [(\"VAR\", [x for x in ts.vars if x not in list(ts.state_vars)+list(ts.input_vars)+list(ts.output_vars)]),\\\n (\"STATE\", ts.state_vars),\\\n (\"INPUT\", ts.input_vars),\\\n (\"OUTPUT\", ts.output_vars)]\n\n for (sname, vars) in sections:\n if len(vars) > 0: self.write(\"%s\\n\"%sname)\n for var in vars:\n sname = self.names(var.symbol_name())\n if var.symbol_type() == BOOL:\n self.write(\"%s : Bool;\\n\"%(sname))\n else:\n self.write(\"%s : BV(%s);\\n\"%(sname, var.symbol_type().width))\n self.write(\"\\n\")\n\n sections = [((ts.init),\"INIT\"), ((ts.invar),\"INVAR\"), ((ts.trans),\"TRANS\")]\n\n for (formula, keyword) in sections:\n if formula not in [TRUE(), FALSE()]:\n self.write(\"%s\\n\"%keyword)\n cp = list(conjunctive_partition(formula))\n if self.simplify:\n cp = self._simplify_cp(cp)\n \n for i in range(len(cp)):\n f = simplify(cp[i])\n if f == TRUE():\n continue\n self.printer(f)\n self.write(\";\\n\")\n if f == FALSE():\n break\n self.write(\"\\n\")\n \n if has_comment:\n self.write(\"\\n%s\\n\"%(\"-\"*lenstr))\n \n\nclass SMVPrinter(HRLTLPrinter):\n\n # Override walkers for SMV specific syntax\n\n def walk_bool_constant(self, formula):\n if formula.constant_value():\n self.write(\"TRUE\")\n else:\n self.write(\"FALSE\")\n\n def walk_bv_constant(self, formula):\n self.write(\"0ud%d_%d\" % (formula.bv_width(), formula.constant_value()))\n\n def walk_bv_zext(self, formula):\n self.write(\"extend \")\n self.write(\"( \")\n yield formula.arg(0)\n self.write(\", %d)\" % formula.bv_extend_step())\n\n def walk_bv_extract(self, formula):\n yield formula.arg(0)\n self.write(\"[%d:%d]\" % (formula.bv_extract_end(),\n formula.bv_extract_start()))\n\n def walk_bv_ashr(self, formula):\n self.write(\"(unsigned(signed(\")\n args = formula.args()\n for s in args[:-1]:\n yield s\n self.write(\") >> \")\n yield args[-1]\n self.write(\"))\")\n\n def walk_bv_ult(self, formula): return self.walk_nary(formula, \" < \")\n\n def walk_bv_ule(self, formula): return self.walk_nary(formula, \" <= \")\n \n def walk_symbol(self, formula):\n if TS.is_prime(formula):\n self.write(\"next(\\\"%s\\\")\"%TS.get_ref_var(formula).symbol_name())\n else:\n self.write(\"\\\"%s\\\"\"%formula.symbol_name())\n\nclass STSPrinter(HRLTLPrinter):\n\n # Override walkers for STS specific syntax\n def walk_symbol(self, formula):\n if TS.is_prime(formula):\n self.write(\"next('%s')\"%TS.get_ref_var(formula).symbol_name())\n else:\n self.write(\"'%s'\"%formula.symbol_name())\n\n def walk_bv_ult(self, formula): return self.walk_nary(formula, \" < \")\n def walk_bv_ule(self, formula): return self.walk_nary(formula, \" <= \")\n def walk_bv_ugt(self, formula): return self.walk_nary(formula, \" > \")\n \n\nclass TracePrinter(object):\n\n def __init__(self):\n pass\n\n def print_trace(self, hts, model, length, map_function=None):\n pass\n\n def get_file_ext(self):\n pass\n\n def is_hidden(self, name):\n return name[:len(HIDDEN)] == HIDDEN\n\nclass TextTracePrinter(TracePrinter):\n\n def __init__(self):\n self.extra_vars = None\n self.diff_only = True\n self.all_vars = False\n\n def get_file_ext(self):\n return \".txt\"\n\n def print_trace(self, hts, modeldic, length, map_function=None, find_loop=False):\n trace = []\n prevass = []\n\n hex_values = False\n \n trace.append(\"---> INIT <---\")\n\n if self.all_vars:\n varlist = list(hts.vars)\n else:\n varlist = list(hts.input_vars.union(hts.output_vars).union(hts.state_vars))\n if self.extra_vars is not None:\n varlist = list(set(varlist).union(set(self.extra_vars)))\n\n strvarlist = [(map_function(var.symbol_name()), var) for var in varlist if not self.is_hidden(var.symbol_name())]\n strvarlist.sort()\n\n for var in strvarlist:\n var_0 = TS.get_timed(var[1], 0)\n if var_0 not in modeldic:\n continue\n varass = (var[0], modeldic[var_0])\n if hex_values:\n varass = (varass[0], dec_to_hex(varass[1].constant_value(), int(var[1].symbol_type().width/4)))\n if self.diff_only: prevass.append(varass)\n trace.append(\" I: %s = %s\"%(varass[0], varass[1]))\n\n if self.diff_only: prevass = dict(prevass)\n\n for t in range(length):\n trace.append(\"\\n---> STATE %s <---\"%(t+1))\n\n for var in strvarlist:\n var_t = TS.get_timed(var[1], t+1)\n if var_t not in modeldic:\n continue\n varass = (var[0], modeldic[var_t])\n if hex_values:\n varass = (varass[0], dec_to_hex(varass[1].constant_value(), int(var[1].symbol_type().width/4)))\n if (not self.diff_only) or (prevass[varass[0]] != varass[1]):\n trace.append(\" S%s: %s = %s\"%(t+1, varass[0], varass[1]))\n if self.diff_only: prevass[varass[0]] = varass[1]\n\n if find_loop:\n last_state = [(var[0], modeldic[TS.get_timed(var[1], length)]) for var in strvarlist]\n last_state.sort()\n loop_id = -1\n for i in range(length):\n state_i = [(var[0], modeldic[TS.get_timed(var[1], i)]) for var in strvarlist]\n state_i.sort()\n if state_i == last_state:\n loop_id = i\n break\n if loop_id >= 0: \n trace.append(\"\\n---> STATE %s loop to STATE %s <---\"%(length, loop_id))\n\n\n trace = NL.join(trace)\n return trace\n\nclass VCDTracePrinter(TracePrinter):\n\n def __init__(self):\n pass\n\n def get_file_ext(self):\n return \".vcd\"\n\n def print_trace(self, hts, modeldic, length, map_function=None):\n hierarchical = False\n ret = []\n\n ret.append(\"$date\")\n ret.append(datetime.datetime.now().strftime('%A %Y/%m/%d %H:%M:%S'))\n ret.append(\"$end\")\n ret.append(\"$version\")\n ret.append(\"CoSA\")\n ret.append(\"$end\")\n ret.append(\"$timescale\")\n ret.append(\"1 ns\")\n ret.append(\"$end\")\n\n def _recover_array(store_ops):\n d = {}\n x = store_ops\n while len(x.args()) == 3:\n next_x, k, v = x.args()\n x = next_x\n if k.constant_value() not in d:\n d[k.constant_value()] = v.constant_value()\n return d\n\n # TODO, use modeldic[v].array_value_assigned_values_map()\n # to get all the array values for a counterexample trace\n modeldic = dict([(v.symbol_name(), modeldic[v].constant_value()\n if not v.symbol_type().is_array_type()\n else _recover_array(modeldic[v])) for v in modeldic])\n\n # These are the pysmt array vars\n arr_vars = list(filter(lambda v: v.symbol_type().is_array_type(), hts.vars))\n\n # Figure out which indices are used over all time\n arr_used_indices = {}\n for av in arr_vars:\n name = av.symbol_name()\n indices = set()\n for t in range(length+1):\n tname = TS.get_timed_name(map_function(name), t)\n indices |= set((k for k in modeldic[tname]))\n arr_used_indices[name] = indices\n\n # These are the vcd vars (Arrays get blown out)\n varlist = []\n arr_varlist = []\n idvar = 0\n var2id = {}\n for v in list(hts.vars):\n n = map_function(v.symbol_name())\n if self.is_hidden(v.symbol_name()):\n continue\n if v.symbol_type() == BOOL:\n varlist.append((n, 1))\n var2id[n] = idvar\n idvar += 1\n elif v.symbol_type().is_bv_type():\n varlist.append((n, v.symbol_type().width))\n var2id[n] = idvar\n idvar += 1\n elif v.symbol_type().is_array_type():\n idxtype = v.symbol_type().index_type\n elemtype = v.symbol_type().elem_type\n for idx in arr_used_indices[n]:\n indexed_name = n + \"[%i]\"%idx\n arr_varlist.append((indexed_name, elemtype.width))\n var2id[indexed_name] = idvar\n idvar += 1\n else:\n Logger.error(\"Unhandled type in VCD printer\")\n\n for el in varlist + arr_varlist:\n (varname, width) = el\n idvar = var2id[varname]\n\n if hierarchical:\n varname = varname.split(SEP)\n for scope in varname[:-1]:\n ret.append(\"$scope module %s $end\"%scope)\n\n ret.append(\"$var reg %d v%s %s[%d:0] $end\"%(width, idvar, varname[-1], width-1))\n\n for scope in range(len(varname)-1):\n ret.append(\"$upscope $end\")\n else:\n varname = varname.replace(SEP, VCD_SEP)\n ret.append(\"$var reg %d v%s %s[%d:0] $end\"%(width, idvar, varname, width-1))\n\n\n ret.append(\"$upscope $end\")\n ret.append(\"$upscope $end\")\n ret.append(\"$enddefinitions $end\")\n\n for t in range(length+1):\n ret.append(\"#%d\"%t)\n for el in varlist:\n (varname, width) = el\n tname = TS.get_timed_name(varname, t)\n val = modeldic[tname] if tname in modeldic else 0\n ret.append(\"b%s v%s\"%(dec_to_bin(val, width), var2id[varname]))\n\n for a in arr_vars:\n name = a.symbol_name()\n width = a.symbol_type().elem_type.width\n tname = TS.get_timed_name(name, t)\n m = modeldic[tname]\n for i, v in m.items():\n vcdname = name + \"[%i]\"%i\n ret.append(\"b%s v%s\"%(dec_to_bin(v,width),var2id[vcdname]))\n\n # make the last time step visible\n # also important for correctness, gtkwave sometimes doesn't read the\n # last timestep's values correctly without this change\n ret.append(\"#%d\"%(t+1))\n\n return NL.join(ret)\n","sub_path":"cosa/printers.py","file_name":"printers.py","file_ext":"py","file_size_in_byte":18094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"98109909","text":"from PySide2.QtWidgets import *\nfrom ui_main import Ui_MainWindow\nimport sys\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n self.setWindowTitle(\"Programa Corretor de CST\")\n\n self.btn_select.clicked.connect(self.open_file)\n self.btn_correct.clicked.connect(self.fix_cst)\n\n def open_file(self):\n self.file = QFileDialog.getOpenFileName(self, \"Selecione o arquivo SPED\")\n self.txt_file.setText(str(self.file[0]))\n\n def fix_cst(self):\n new_sped = []\n\n with open(self.txt_file.text(), 'r+') as line:\n for reg in line:\n\n if reg[:6] == '|C170|':\n new_file = list(reg.split('|'))\n\n for dados in new_file:\n if dados == self.txt_cfop.text():\n new_file[10] = self.txt_cst_icms.text()\n new_file[20] = self.txt_cst_ipi.text()\n\n aux = ('|'.join(new_file))\n new_sped.append(aux)\n continue\n new_sped.append(reg)\n\n with open('fixed_efd.txt', 'w+') as fixed:\n\n for lin in new_sped:\n fixed.writelines(lin)\n\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setWindowTitle(\"Correcao\")\n msg.setText('Correcao do CST concluida')\n msg.exec_()\n\n\nif __name__== '__main__':\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n app.exec_()","sub_path":"Corrector_CST-ICMS_and_CST-IPI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"538711644","text":"# MT: modifications by Mengting\n\nimport sys\nimport numpy as np\nimport random\nfrom model_settings import img_height, img_width, min_edge, max_edge, min_blobs_train, max_blobs_train, min_blobs_test, max_blobs_test # MT\n\ndef set_size(num_blobs, even=None):\n \"\"\"Get amount of images for each number\"\"\" \n if even is None:\n return int(10000/(num_blobs**2)) # uneven: number distribution 1/(n^2)\n else:\n return 1000 # even: make 1000 images for each number\n\ndef get_total(even, min_blobs, max_blobs): # MT\n \"\"\"Get total amount of images.\"\"\"\n c = min_blobs\n total = 0\n while (c < max_blobs + 1):\n total = total + set_size(c, even)\n c = c + 1\n return total\n\ndef generate_data(even, min_blobs, max_blobs): # MT\n n_labels = max_blobs_train - min_blobs_train + 1 \n total = get_total(even, min_blobs, max_blobs)\n train = np.zeros([total, img_height*img_width]) # input img size\n label = np.zeros([total, n_labels])\n num_blobs = min_blobs\n img_count = 0\n \n while (num_blobs < max_blobs + 1):\n\n nOfItem = set_size(num_blobs, even) # even, 1000; uneven, 10000/(num_blobs**2)\n i = 0 # amount of images for each blob number\n\n while (i < nOfItem):\n img = np.zeros(img_height*img_width) # input img size\n num_count = 0 # amount of blobs in each image \n used = np.zeros((num_blobs, 4)) # check overlapping\n\n while num_count < num_blobs: \n height = random.randint(min_edge, max_edge)\n #width = random.randint(min_edge, max_edge)\n width = height # for square blobs\n #cX = random.randint(1 * num_blobs * 10, 50-width + num_blobs * 10)\n #cY = random.randint(1 * num_blobs * 10, 50-height + num_blobs * 10)\n cX = random.randint(1, 99-width) # top left corner\n cY = random.randint(1, 99-height)\n \n index = 0\n \n while index < num_count:\n if cX+width+1 <= used[index, 0] or used[index, 0]+1+used[index, 2] <= cX or used[index, 1]+1+used[index,3] <= cY or cY+height+1<=used[index,1]:\n index = index + 1\n else:\n cX = random.randint(1, 99-width)\n cY = random.randint(1, 99-height)\n index = 0\n \n used[index, 0] = cX\n used[index, 1] = cY\n used[index, 2] = width\n used[index, 3] = height\n\n for p in range(cY, cY+height):\n for q in range(cX, cX+width): \n img[p*img_width+q] = 255\n num_count += 1\n \n train[img_count] = img\n label[img_count, num_blobs - 1] = 1\n img_count += 1\n i += 1\n \n num_blobs += 1\n \n np.set_printoptions(threshold=np.nan)\n\n# if empty_img:\n# train = np.vstack((train, np.zeros((1000, 10000))))\n# for empty_idx in range(1000):\n# empty_label = np.zeros(max_blobs + 1)\n# empty_label[0] = 1\n# label = np.vstack((label, empty_label))\n\n return train, label\n","sub_path":"scalar_models/HiddenAnalysis/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"629944401","text":"class Helper:\r\n \"\"\"\r\n Container for helper functions\r\n \"\"\"\r\n\r\n @staticmethod\r\n def chunks(l, n):\r\n \"\"\"\r\n Yield successive n-sized chunks from l.\r\n \"\"\"\r\n for i in range(0, len(l), n):\r\n yield l[i:i + n]\r\n\r\n @staticmethod\r\n def find_pattern(header, pattern):\r\n \"\"\"\r\n find pattern in the header and return the amount of columns. For example:\r\n\r\n pattern = 1,2,3\r\n\r\n header = 1,2,3,1,2,3,1,2,3,6,7,8,9\r\n\r\n return 9, because (1,2,3),(1,2,3),(1,2,3),6,7,8,9\r\n\r\n :param header: tuple where to look for patter\r\n :param pattern: actual pattern\r\n :return:\r\n \"\"\"\r\n # idea is to loop over the header\r\n if len(header) < len(pattern):\r\n raise ValueError(\"Pattern length is bigger than a header length\")\r\n else:\r\n # chunk the header into pattern sized parts\r\n chunked_header = list(Helper.chunks(header, len(pattern)))\r\n for indx, subheader in enumerate(chunked_header):\r\n if subheader != pattern:\r\n indx = indx - 1\r\n break\r\n return (indx+1) * len(pattern)\r\n","sub_path":"src/validpanda/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394801007","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 23 12:58:44 2015\r\n\r\n@author: nicolas\r\n\"\"\"\r\n\"\"\"\r\nLa classe Polynome sert à manipuler simplement des polynômes. Voici quelques\r\nexemples d utilisation (les \">>>\" indiquent que la ligne est une commande \r\npassée à l interpréteur Python, les autres lignes sont les réponses de\r\nPython):\r\n \r\nCréation: en donnant la liste des coefficients \r\n=========\r\n >>> P = Polynome([1, 0, 5])\r\n >>> P\r\n 5*X**2 + 1\r\n >>> X = Polynome([0, 1])\r\n >>> X**n\r\n X**n\r\n \r\nAccès et modification :\r\n=======================\r\n >>> P = Polynome([1, 0, 5])\r\n >>> P[2] # le coefficient devant X^2\r\n 5\r\n >>> P[3] # le coefficient devant X^3 (il n'y en a pas)\r\n 0\r\n >>> P[0] # le terme constant\r\n 1\r\n >>> P.lead # lead pour leader : le coefficient dominant de P\r\n 5\r\n >>> P.deg # le degré de P\r\n 2\r\n >>> P[2] = 4 # on change le coefficient devant X^2\r\n >>> P\r\n 4X^2 + 1\r\n >>> P[5] = 3 # on rajoute un coefficient\r\n >>> P\r\n 3*X**5 + 4X**2 + 1\r\n >>> P.deg # le degré est-il bien mis à jour ?\r\n 5 # oui !\r\n >>> P.lead\r\n 3\r\n \r\n/!\\ Un polynôme ressemble à une liste, mais n est pas une liste ! En particulier\r\n‾‾‾ les méthodes \"append\" et \"len\" ne s appliquent pas à un polynôme.\r\n \r\nOpérations algébriques : tout ce que vous révez de faire avec des polynômes\r\n========================\r\n \r\n >>> P = Polynome([1, 0, 5])\r\n >>> P * P\r\n 25*X**4 + 10*X**2 + 1\r\n >>> P + 5\r\n 5*X**2 + 6\r\n >>> P ** 3 # puissance\r\n 125*X**6 + 75*X**4 + 15*X**2 + 1\r\n >>> (P * P) // (P + 5) # quotient de la division euclidienne\r\n 5*X**2 - 4\r\n >>> (P * P) % (P + 5) # reste de la division euclidienne\r\n 25\r\n >>> X = Polynome([0,1])\r\n >>> (5*X**2 - 4) * (P + 5) + 25 - (P* P) # vérification\r\n 0 # youpi !\r\n\"\"\"\r\n \r\n################################################################################\r\n# IGNOREZ LES LIGNES SUIVANTES JUSQU'AU PROCHAIN #\r\n# ENCART VOUS INVITANT À LIRE #\r\n################################################################################\r\n\r\nfrom numbers import Number\r\nfrom fractions import Fraction\r\nclass Polynome:\r\n \"\"\"\r\n WARNING : this class is written for educational purpose; the algorithms\r\n used are unefficient with polynomials of high degree. Consider a real\r\n lib if you have to deal with big polynomials.\r\n \"\"\"\r\n \r\n def __init__(self, coeffs):\r\n \"\"\" Construit un polynôme à partir d'une liste de coefficients.\r\n \r\n coeffs: liste des coefficients, le terme constant est dans coeffs[0],\r\n le terme en X est dans coeffs[1], ...\r\n \"\"\"\r\n self._coeffs = [Fraction(c) for c in coeffs]\r\n self._compute_deg(len(coeffs)-1)\r\n \r\n @property\r\n def deg(self):\r\n return self._deg\r\n \r\n @property\r\n def lead(self):\r\n \"Renvoie le coefficient dominant de self (0 si self.deg < 0)\"\r\n if self.deg < 0:\r\n return 0\r\n return self[self.deg]\r\n \r\n def __getitem__(self, i):\r\n \"\"\"Renvoie le coefficient devant x^i. Lance une erreur si i < 0, renvoie\r\n 0 si i > deg.\"\"\"\r\n if i < 0:\r\n raise ValueError(\"l'indice doit être positif\")\r\n \r\n if i <= self.deg:\r\n return self._coeffs[i]\r\n else:\r\n return 0\r\n \r\n def __setitem__(self,i, coeff):\r\n \"\"\"Modifie le coefficient devant x^i. Lance une erreur si i < 0.\r\n Met le degré à jour si besoin.\"\"\"\r\n if i < 0:\r\n raise ValueError(\"l'indice doit être positif\")\r\n \r\n n = len(self._coeffs)\r\n self._coeffs.extend([0] * (i-n +1))\r\n self._coeffs[i] = coeff\r\n if i > self._deg and coeff != 0:\r\n self._deg = i\r\n elif i == self.deg and coeff == 0:\r\n self._compute_deg(i-1)\r\n \r\n def _compute_deg(self, dmax):\r\n \"\"\" Met à jour le veritable degré du polynôme en ignorant les 0 en fin\r\n de liste, en supposant que tous les éléments de self._coeffs sont\r\n nuls aux indices supérieurs strictement à dmax.\"\"\"\r\n while dmax >= 0 and self._coeffs[dmax] == 0:\r\n dmax -= 1\r\n self._deg = dmax\r\n \r\n def __add__(self, p2):\r\n \"\"\" Renvoie la somme de self et p2. p2 peut être un polynôme ou un \r\n nombre (hérite de Number).\"\"\"\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n raise ValueError(\"on ne peut additionner un polynôme\"\r\n \"qu'avec un nombre ou un polynôme\")\r\n \r\n deg = max(self.deg, p2.deg)\r\n coeffs = [0] * (deg +1)\r\n for i in range(deg + 1):\r\n coeffs[i] = self[i] + p2[i]\r\n return Polynome(coeffs)\r\n \r\n __radd__ = __add__\r\n \r\n def __sub__(self, p2):\r\n \"\"\" Renvoie la différence de self et p2. p2 peut être un polynôme ou un \r\n nombre (hérite de Number).\"\"\"\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n raise ValueError(\"on ne peut soustraire un polynôme\"\r\n \"qu'avec un nombre ou un polynôme\")\r\n \r\n deg = max(self.deg, p2.deg)\r\n coeffs = [0] * (deg + 1)\r\n for i in range(deg + 1):\r\n coeffs[i] = self[i] - p2[i]\r\n return Polynome(coeffs)\r\n \r\n def __rsub__(self, p2) : \r\n \"\"\" Renvoie la différence de p2 et self. p2 peut être un polynôme ou un \r\n nombre (hérite de Number).\"\"\"\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n raise ValueError(\"on ne peut soustraire un polynôme\"\r\n \"qu'avec un nombre ou un polynôme\")\r\n \r\n deg = max(self.deg, p2.deg)\r\n coeffs = [0] * (deg +1)\r\n for i in range(deg + 1):\r\n coeffs[i] = p2[i] - self[i]\r\n return Polynome(coeffs)\r\n \r\n def __neg__(self):\r\n \"\"\"Renvoie le polynôme opposé de self.\"\"\"\r\n return Polynome([-c for c in self._coeffs])\r\n \r\n def __mul__(self, p2):\r\n \"\"\" Renvoie le produit de self et p2. p2 peut être un polynôme ou un \r\n nombre (hérite de Number).\"\"\"\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n raise ValueError(\"on ne peut multiplier un polynôme\"\r\n \"qu'avec un nombre ou un polynôme\")\r\n \r\n deg = self.deg + p2.deg\r\n coeffs = [0] * (deg + 1)\r\n for i in range(self.deg + 1):\r\n for j in range(p2.deg + 1):\r\n coeffs[i+j] += self._coeffs[i] * p2._coeffs[j]\r\n return Polynome(coeffs)\r\n \r\n __rmul__ = __mul__\r\n \r\n def __pow__(self, n):\r\n \"\"\" Renvoie self**n. \"\"\"\r\n if n < 0:\r\n raise ValueError(\"seule les puissances entieres positives sont\"\r\n \"définies\")\r\n \r\n res = Polynome([1])\r\n for i in range(n):\r\n res *= self\r\n return res\r\n \r\n def __eq__(self, p2):\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n return False\r\n if self.deg < 0 and p2.deg < 0:\r\n return True\r\n \r\n return ( self.deg == p2.deg and\r\n self._coeffs[:p2.deg + 1] == p2._coeffs[:p2.deg + 1])\r\n \r\n def quo_rem(self, p2):\r\n \"\"\"Renvoie le quotient et le reste de la division euclidienne de\r\n self par p2.\"\"\"\r\n if isinstance(p2, Number):\r\n p2 = Polynome([p2])\r\n elif not isinstance(p2, Polynome):\r\n raise ValueError(\"on ne peut diviser un polynôme\"\r\n \"qu'avec un nombre ou un polynôme\")\r\n \r\n if p2.deg < 0:\r\n raise ValueError(\"impossible de diviser par 0\")\r\n \r\n x = Polynome([0,1])\r\n q = Polynome([0] * (self.deg - p2.deg))\r\n r = Polynome(self._coeffs[:self.deg + 1])\r\n while r.deg >= p2.deg:\r\n coeff = r.lead / p2.lead\r\n deg = r.deg - p2.deg\r\n xd = x**deg\r\n q += coeff * xd\r\n r -= coeff * xd * p2\r\n return q, r\r\n \r\n def __mod__(self, p2):\r\n return self.quo_rem(p2)[1]\r\n \r\n def __floordiv__(self, p2):\r\n return self.quo_rem(p2)[0]\r\n \r\n \r\n def _monome_to_str(self, d, debut):\r\n \"\"\" Renvoie une représentation textuelle du monome de degré d de self.\r\n Si debut est à True et le coefficient est positif, il n'y aura pas\r\n de signe \"+\" au début de la chaîne de caractères.\r\n Si debut est à False, il y aura toujours un signe \"+\" ou \"-\" devant\r\n le monome.\r\n Si le coefficient est nul, renvoie la chaine vide.\r\n \"\"\"\r\n coeff = self[d]\r\n if coeff == 0:\r\n return \"\"\r\n \r\n if coeff > 0:\r\n if debut:\r\n signe =\"\"\r\n else:\r\n signe = \" + \"\r\n else:\r\n coeff *= -1\r\n if debut:\r\n signe = \"-\"\r\n else:\r\n signe = \" - \"\r\n \r\n if d == 0:\r\n res = signe + str(coeff)\r\n else:\r\n if coeff == 1:\r\n res = signe + \"X\"\r\n else:\r\n res = signe + str(coeff) + \"*X\"\r\n \r\n if d > 1:\r\n res += \"**\" + str(d)\r\n return res \r\n \r\n def __str__(self):\r\n \"\"\" Renvoie une représentation textuelle de P.\"\"\"\r\n if self.deg < 0:\r\n return \"0\"\r\n \r\n s = self._monome_to_str(self.deg, True)\r\n for i in range(self.deg - 1, -1, -1):\r\n s += self._monome_to_str(i, False)\r\n return s\r\n \r\n def gcd(self, p2):\r\n \"\"\" Renvoie le pgcd de self et p2.\"\"\"\r\n if p2.deg < 0:\r\n return self\r\n if self.deg < p2.deg:\r\n return p2.gcd(self)\r\n \r\n return p2.gcd(self % p2)\r\n \r\n def square_free(self):\r\n \"\"\" Renvoie le radical de self.\r\n \r\n Si self est un produit de polynomes irréductibles P_i à une certaine\r\n puissance, le radical de self est le produit des P_i à la puissance\r\n 1.\"\"\"\r\n t = Polynome([i*c for i, c in enumerate(self._coeffs)])\r\n return self // self.gcd(t)\r\n \r\n __repr__ = __str__\r\n \r\n \r\n################################################################################\r\n# #\r\n# REPRENDRE LA LECTURE ! #\r\n# #\r\n################################################################################\r\n \r\n# Questions préliminaires, pour être sûr d'avoir bien compris comment utiliser\r\n# les polynômes:\r\n# 0. Quel polynôme est construit par l'instruction Polynome([0,1,2,3])\r\n# 1. Construire le polynôme X^52 + 3X^2 +1 (plusieurs lignes peuvent \r\n# être nécessaires).\r\n# 2. Donner 2 moyens de connaître le coefficient dominant d'un polynôme P\r\n# 3. Comment accéder au terme constant d'un polynôme P?\r\n# 4. Calculer le reste de la division de 5X^42 + 3X+1 par 42 X^12 +3X-2.\r\n# 5. Si P est un polynôme, comment tester que P est le polynôme nul?\r\n \r\n# Consigne: écrire le corps des fonctions données. Laisser la docstring\r\n# (la chaine de caractères sous la fonction la documentant). TESTER ABONDAMMENT\r\n# CHAQUE FONCTION APRÈS L'AVOIR ÉCRITE ! Exemple:\r\n \r\n# AVANT votre passage:\r\ndef quarante_deux_fois(x):\r\n \"\"\"Renvoie la multiplication de 42 par x.\"\"\"\r\n return 0\r\n \r\n# APRÈS votre passage:\r\ndef quarante_deux_fois(x):\r\n \"\"\"Renvoie la multiplication de 42 par x.\"\"\"\r\n res = 0\r\n for i in range(9):\r\n for j in range(5):\r\n res += x\r\n return res - x - x - x\r\n# Évidemment, il y a mieux pour écrire cette fonction....\r\n \r\n# Sauf mention explicite dans la documentation, les fonctions ne modifient pas\r\n# leurs arguments. De plus, lorsque la documentation d'une fonction indique que \r\n# ses arguments sont d'un certain type, on fera confiance à l'utilisateur et\r\n# on ne vérifiera pas les types. \r\n \r\n# Les fonctions obligatoires pour le DM sont : bin, eval_poly, derivative et\r\n# sturm_sequence. Vous m'enverrez le fichier à l'adresse \r\n# monsieurbesnier@gmail.com\r\n# avant mardi soir, 19h, cachet du mail faisant foi. Vous nommerez votre fichier\r\n# \"nom_prenom_dm6.py\" (sans accent, ni espaces ni caractères spéciaux). Par \r\n# exemple pour moi ce serait \"sebastien_besnier_dm6.py\"\r\n \r\n# Avis aux élèves tentés de faire un copier/coller sauvage à partir du code du\r\n# voisin, pour après changer quelques noms de variables : cela se repère \r\n# extrèmement facilement. Il y a même des outils qui font ça automatiquement. Et \r\n# ils fonctionnent très bien.\r\n \r\n# Just for fun, sans lien avec la suite\r\ndef binomial(k, n):\r\n \"\"\" Renvoie le coefficient binomial \"k parmi n\"... en 1 seule ligne !\r\n (indication: (X+1)^n )\r\n \"\"\"\r\n P=(Polynome([1,1]))**n\r\n return P[k] # 1 ligne ?\r\n\r\ndef eval_poly(P, x):\r\n \"\"\" Renvoie P(x).\r\n \r\n Entrées:\r\n P: polynôme\r\n x: nombre\r\n \r\n Algorithme: si vous ne voulez pas vous embêter, utilisez la formule brutale,\r\n qui consiste à faire la somme des a_i x^i.\r\n Si vous voulez être un peu plus efficace, utilisez l'algorithme \r\n \"d'Hörner\" pour réduire le nombre\r\n de multiplications pour avoir x**n. Par exemple, si P = aX^3 + bX^2 + cX +d,\r\n on calcule P(x) grâce à:\r\n P(x) = d + x (c + x (b + a x)))\r\n (on commence donc le calcul par le terme de plus haut degré).\r\n \r\n Exemples:\r\n >>> X = Polynome([0,1])\r\n >>> eval_poly(5*X**2 + 1, 0)\r\n 1\r\n >>> eval_poly(5*X**2 + 1, 1)\r\n 6\r\n >>> eval_poly(5*X**2 + 1, 2)\r\n 21\r\n >>> eval_poly(5*X**2 + 1, 3)\r\n 46\r\n \"\"\"\r\n res=P.lead\r\n for i in range(P.deg-1,-1,-1):\r\n res=res*x+P[i]\r\n return res\r\n \r\ndef derivative(P):\r\n \"\"\" Renvoie le polynôme dérivé de P.\r\n \r\n Exemples:\r\n >>> X = Polynome([0,1])\r\n >>> derivative(X**2)\r\n 2*X\r\n >>> derivative(5*X**3 - 6*X +3)\r\n 15*X**2 - 6\r\n \"\"\"\r\n Pder=Polynome([0])\r\n for i in range(P.deg):\r\n Pder[i]=(i+1)*P[i+1]\r\n return Pder\r\n \r\n \r\ndef sturm_sequence(P):\r\n \"\"\" Renvoie la suite de Sturm de P sous forme de liste [P_0, P_1, ..., P_m].\r\n \r\n La suite de Sturm est définie par (l'expression \"A%B\" désigne le reste de la\r\n division euclidienne de A par B):\r\n P_0 = P\r\n P_1 = P'\r\n P_{k+2} = - P_{k} % P_{k+1}, pour k entier naturel.\r\n Le dernier terme P_m est tel que P_{m-1} % P_m = 0.\r\n \r\n Exemple:\r\n >>> P = Polynome([-1, 9, -6, 1])\r\n >>> sturm_sequence(P)\r\n [X**3 - 6*X**2 + 9*X - 1, 3*X**2 - 12*X + 9, 2*X - 5, 9/4]\r\n \"\"\"\r\n Pi=P\r\n Pj=derivative(Pi)\r\n L=[Pi,Pj]\r\n while Pj.deg!=0:\r\n Pi,Pj=Pj,-(Pi%Pj)\r\n L.append(Pj)\r\n return L\r\n \r\ndef nb_change_sign_at(polys, x):\r\n \"\"\" Calcule le nombre de changements de signes lorsqu'on évalue les \r\n polynomes dans polys en x. Un zéro n'est pas considéré comme un changement\r\n de signe.\r\n \r\n Entrées:\r\n polys: liste de polynômes\r\n x: un nombre.\r\n \r\n Exemple:\r\n >>> X = Polynome([0, 1])\r\n >>> nb_change_sign_at([X, X**2+1, X+2], -1)\r\n 1 # on a \"-1, 2, 1\" soit la chaîne de signes \"-++\", donc 1 changement\r\n >>> nb_change_sign_at([X, X**2+1, X-2], -1)\r\n 2 # on a \"-1, 2, -3\" soit la chaîne de signes \"-+-\", donc 2 changements\r\n \"\"\" \r\n chgmt=0\r\n i=0\r\n while i<(len(polys)-1):\r\n j=i+1\r\n # eval_poly(polys[i],x) est évalué à chaque fois alors qu'il ne change\r\n # pas lorsque j varie. On peut n'évaluer qu'une seule fois chaque\r\n # polynomes de polys, ce qui est loin d'être ton cas. Voir correction.\r\n while j=0:\r\n j+=1\r\n if j 0 tel que toutes les racines de P soient dans \r\n l'intervalle [-M, M].\r\n \r\n Indication: voir exercice 21 du chapitre sur les polynômes (attention,\r\n dans l'exercice 21, le polynôme est supposé unitaire).\r\n \"\"\"\r\n M=0\r\n for i in range(P.deg-1):\r\n M+=abs(P[i]/P.lead) # le \"-\" est bouffé par le \"abs\". Factorise le \"/P.lead\".\r\n if M<1:\r\n M=1\r\n return M\r\n \r\ndef nb_roots(polys):\r\n \"\"\" Renvoie le nombre de racines réelles du premier polynôme de polys,\r\n quand polys est une suite de Sturm.\r\n \r\n Entrées:\r\n polys: une liste de polynômes, plus exactement, polys est la suite de\r\n Sturm de polys[0].\r\n \"\"\"\r\n M=roots_range(polys[0]) +1 # M peut être une racine.\r\n nb_roots=nb_roots_between(polys, -M, M)\r\n return nb_roots\r\n \r\ndef find_root(P, a, b, eps):\r\n \"\"\" Trouve une racine de p dans [a,b[, sachant que p(a) * p(b) <= 0.\r\n Renvoie une approximation de la racine à eps près.\r\n \r\n Algorithme : utiliser une dichotomie.\r\n \"\"\"\r\n if eval_poly(P,a)==0:\r\n return a\r\n deb=a\r\n fin=b\r\n mil=(a+b)/2\r\n while abs(eval_poly(P,mil))>abs(eps):\r\n if eval_poly(P,mil)*eval_poly(P,a)<0:\r\n fin=mil\r\n elif eval_poly(P,mil)*eval_poly(P,b)<0:\r\n deb=mil\r\n else:\r\n return mil\r\n mil=(deb+fin)/2\r\n return mil\r\n \r\n \r\ndef isolate_roots(P):\r\n \"\"\" Renvoie une liste de nombres [x_0, x_1, ..., x_n]\r\n rangés dans l'ordre croissant telle qu'il existe une unique racine de P \r\n entre chaque x_i et x_{i+1}. \r\n \r\n Cette fonction est déjà implémentée et fonctionnera\r\n correctement sous réserve que toutes les fonctions ci-dessus sont \r\n correctement implémentées.\r\n \"\"\"\r\n polys = sturm_sequence(P)\r\n M = 2*roots_range(P)\r\n \r\n def loop(a, b, n_prev):\r\n \"\"\"Renvoie une liste [c_0, c_1, ..., c_m] telle que chaque intervalle de\r\n la liste [a, c_0, c_1, ..., c_m, b] contienne exactement une racine de\r\n P. n_prev contient le nombre de racines de P entre a et b.\"\"\"\r\n if n_prev == 1 or n_prev == 0:\r\n return []\r\n \r\n c = (a + b) / 2.\r\n n = nb_roots_between(polys, a, c)\r\n \r\n if n == n_prev:\r\n return loop(a, c, n)\r\n if n == 0:\r\n return loop(c, b, n_prev)\r\n return loop(a, c, n) + [c] + loop(c, b, n_prev -n)\r\n \r\n return [-M] + loop(-M, M, nb_roots_between(polys, -M, M)) + [M]\r\n \r\ndef roots(P, eps):\r\n \"\"\" Renvoie la liste des racines de P avec une précision eps.\r\n On pourra calculer le radical de P, qui a même racines que P mais qui n'a\r\n pas de facteurs carrés; pour cela, on peut tout simplement utiliser\r\n P.square_free().\r\n \"\"\"\r\n L=[]\r\n for i in range(len(isolate_roots(P.square_free()))-1):\r\n # Plusieurs appels à P.square_free()... Un seul suffit !\r\n # 3 appels à isolate_roots... Idem !\r\n L.append(find_root(P.square_free(), isolate_roots(P.square_free())[i], isolate_roots(P.square_free())[i+1], eps))\r\n return L\r\n \r\n# Conclusion : À part quelques appels de fonctions superflux, c'est très bien.\r\n","sub_path":"coulombeau.py","file_name":"coulombeau.py","file_ext":"py","file_size_in_byte":20393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"242259021","text":"#!/usr/bin/env python2\n# encoding: utf-8\n\n# 该文件用于提取网页的正文部分,针对通用型网页\n\nimport re\nimport time\nimport lxml\nimport random\nfrom utils.utils import Utils\nimport lxml.html.soupparser as soupparser\n\n\n# 通用型页面内容提取方法\nclass ExtractContent(object):\n\n def __init__(self):\n pass\n\n\n # 去除javascript、stylesheet、注释( and )\n def remove_js_css(self, content):\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub('', content)\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub('', s)\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub('', s)\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub('', s)\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub('', s)\n return s\n\n\n # 去除多空行\n def remove_empty_line(self, content):\n r = re.compile(r'''^\\s+$''', re.M|re.S)\n s = r.sub('', content)\n r = re.compile(r'''\\n+''', re.M|re.S)\n s = r.sub('\\n', s)\n return s\n\n\n def remove_any_tag(self, s):\n s = re.sub(r'''<[^>]+>''', '', s)\n return s.strip()\n\n\n def remove_any_tag_but_a(self, s):\n text = re.findall(r''']*>(.*?)''', s, re.I|re.M|re.S)\n text_b = self.remove_any_tag(s)\n return len(''.join(text)), len(text_b)\n\n\n def remove_image(self, s, n=5):\n image = 'a' * n\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub(image, s)\n return s\n\n\n def remove_video(self, s, n=10):\n video = 'a' * n\n r = re.compile(r'''''', re.I|re.M|re.S)\n s = r.sub(video, s)\n return s\n\n\n def sum_max(self, values):\n cur_max = values[0]\n glo_max = -999999\n left, right = 0, 0\n for index, value in enumerate(values):\n cur_max += value\n if (cur_max > glo_max):\n glo_max = cur_max\n right = index\n elif (cur_max < 0):\n cur_max = 0\n\n for i in range(right, -1, -1):\n glo_max -= values[i]\n if abs(glo_max) < 0.00001:\n left = i\n break\n\n return left, right+1\n\n\n # 根据密度提取正文\n def method_1(self, content, k=1, delta=8):\n tmp = content.split('\\n')\n group_value = []\n\n for i in range(0, len(tmp), k):\n group = '\\n'.join(tmp[i:i+k])\n group = self.remove_image(group)\n group = self.remove_video(group)\n text_a, text_b = self.remove_any_tag_but_a(group)\n temp = (text_b - text_a) - delta\n group_value.append(temp)\n\n left, right = self.sum_max(group_value)\n return left, right, len('\\n'.join(tmp[:left])), len('\\n'.join(tmp[:right]))\n\n\n # 根据常见的main模块的xpath, 预先提取出大致正文\n def get_main_block(self, response):\n response.encoding = Utils.get_response_encoding(response)\n\n try:\n tree = soupparser.fromstring(response.text)\n\n for t in ['main', 'main_content']:\n path = \"//body//div[@class='{}']\".format(t)\n content = tree.xpath(path)\n if content:\n return ''.join([lxml.etree.tostring(i, encoding='utf8', method='html') for i in content])\n\n for t in ['main_content']:\n path = \"//body//div[@id='{}']\".format(t)\n content = tree.xpath(path)\n if content:\n return ''.join([lxml.etree.tostring(i, encoding='utf8', method='html') for i in content])\n\n except:\n return response.text\n\n return response.text\n\n\n # 重新整理段落格式\n def rearrage_paragraph(self, content):\n all_p = re.findall(r'''(.*?)

''', content, re.I | re.M | re.S)\n if not all_p or list(set(all_p)) == ['']:\n r = re.compile(r'<.*?>', re.I | re.M | re.S)\n s = r.sub(' ', content)\n else:\n r = [lxml.etree.HTML('

' + i + '

').xpath('//p')[0].xpath('string(.)') for i in all_p]\n s = '\\n'.join(r)\n return s.strip()\n\n\n # 替换一些html的特殊字符\n def substring(self, text):\n if text:\n text = re.sub(' ', ' ', text)\n text = re.sub('>', '>', text)\n text = re.sub('<', '<', text)\n return text\n\n\n # 本类主函数, 通用型网页正文提取\n def extract_content(self, response):\n try:\n content = self.get_main_block(response)\n content = self.remove_empty_line(self.remove_js_css(content))\n left, right, x, y = self.method_1(content)\n\n content = '\\n'.join(content.split('\\n')[left:right])\n content = Utils.transform_coding(content)\n content = self.rearrage_paragraph(content)\n content = self.substring(content)\n return content\n\n except:\n return ''\n\n\n\n# 通用的、提取item信息\nclass CommonExtract(object):\n\n def __init__(self):\n pass\n\n\n def parse_response(self, response, item):\n ec = ExtractContent()\n content = ec.extract_content(response)\n item.content = content.strip('\\n')\n\n\n","sub_path":"extract/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"549560734","text":"import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scraping.scraping.items import ForecastItem\n\n\nclass ForecastSpider(CrawlSpider):\n name = \"forecast\"\n allowed_domains = [\"tenki.jp\"]\n start_urls = [\"https://tenki.jp/indexes/dress/\"]\n\n rules = (\n Rule(LinkExtractor(allow=r\"/indexes/dress/\\d+/\\d+/\"), callback=\"parse_item\"),\n )\n\n def parse_item(self, response):\n item = ForecastItem()\n\n place = response.css(\"#delimiter ol li a span::text\").extract()\n item[\"area\"] = place[-2]\n item[\"prefecture\"] = place[-1]\n\n item[\"update_time\"] = response.css(\".date-time ::text\").extract_first()\n\n item[\"clothes_info\"] = response.css(\".map-wrap ul span ::text\").extract()\n\n for forecast in response.css(\".sub-column-forecast-pickup\"):\n item[\"weather_city\"] = forecast.css(\".name ::text\").extract()\n item[\"weather\"] = forecast.css(\"img::attr(alt)\").extract()\n\n item[\"highest_temp\"] = forecast.css(\n \".date-value .high-temp ::text\"\n ).extract()\n item[\"lowest_temp\"] = forecast.css(\".date-value .low-temp ::text\").extract()\n\n item[\"rain_chance\"] = forecast.css(\".precip ::text\").extract()\n yield item\n","sub_path":"services/web/scraping/scraping/spiders/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"566195739","text":"# encoding: utf-8\n\"\"\"\nNOTE:\n 存在重复的三元组,这里没有去掉。\n ConceptNet格式是relation, entity, predict,其他KG是entity, relation, predict\n\"\"\"\n\nimport sys\n\nif __name__ == '__main__':\n while True:\n line = sys.stdin.readline().strip()\n if line:\n items = line.split('\\t')\n relation = items[1]\n entity = items[2]\n predict = items[3]\n relation = relation.split('/')[-1]\n entity_lang, entity = entity.split('/')[2:4]\n predict_lang, predict = predict.split('/')[2:4]\n if entity_lang == 'zh' or predict_lang == 'zh':\n print('\\t'.join((relation, entity, predict,)))\n else:\n break\n","sub_path":"corpus_processor/kg/concept_net_extractor.py","file_name":"concept_net_extractor.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"453587303","text":"import os\n\n\ndef getWordList(filepath):\n assert os.path.isfile(filepath), 'Must be a file'\n txt = open(filepath).read().strip().split('\\n')\n if ':' in open(filepath).read():\n for line in txt:\n if ':' not in line:\n txt[txt.index(line)] = line + ':'\n words = {}\n for line in txt:\n index = line.split(':')[0]\n words[index] = line.split(':')[1].split(',')\n for syn in words[index]:\n if syn == '':\n words[index].remove(syn)\n else:\n words = []\n for word in txt:\n words.append(word.strip())\n return words\n\n\nverbs = getWordList('src/dictionary/verbs.txt')\nnouns = getWordList('src/dictionary/nouns.txt')\nextras = getWordList('src/dictionary/extras.txt')\n","sub_path":"src/words.py","file_name":"words.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"446070895","text":"import random\n\nimport pytest\n\nfrom day19 import full_beacon_list, matcher, max_manhattan_between_scanners, verify\nfrom geometry_utils import Vector, all_cubic_group_transformations, invert\nfrom helpers import parse_file\n\n\n@pytest.fixture\ndef data_test():\n data = parse_file(\"test.txt\")\n assert len(data) == 5\n return data\n\n\n@pytest.fixture\ndef real_data():\n data = parse_file(\"input.txt\")\n return data\n\n\ndef test_match_scanner_1_and_scanner_2(data_test):\n result = matcher(data_test[0], data_test[1])\n assert result\n translation, rotation = result\n assert (\n len(\n set(data_test[0]).intersection(\n set((rotation.apply(b) + translation) for b in data_test[1])\n )\n )\n == 12\n )\n\n\ndef test_full_beacon_list(data_test):\n all_beacons, all_pos = full_beacon_list(data_test)\n assert len(all_beacons) == 79\n assert max_manhattan_between_scanners(all_pos) == 3621\n\n\ndef test_with_real_data(real_data):\n all_beacons, positions = full_beacon_list(real_data)\n print(\"number of beacons:\", len(all_beacons))\n assert len(all_beacons) == 405\n d_max = max_manhattan_between_scanners(positions)\n print(d_max)\n\n\n@pytest.mark.parametrize(\"rotation\", list(all_cubic_group_transformations))\ndef test_matcher(rotation):\n initial_source = {\n Vector(\n (random.randint(0, 1000), random.randint(0, 999), random.randint(0, 999))\n )\n for _ in range(30)\n }\n translation_vector = Vector((345, 789, 123))\n other_beacon = {rotation.apply(b + translation_vector) for b in initial_source}\n tr, rot = verify(\n initial_source,\n other_beacon,\n Vector((-1) * v for v in translation_vector),\n invert(rotation),\n )\n assert tr, rot == matcher(initial_source, other_beacon)\n","sub_path":"2021/day19/test_algorithm_solution.py","file_name":"test_algorithm_solution.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"484327410","text":"import random\nfrom freq import freq\nfrom cons import cons\nfrom lib_vowels import lib_vowels\n\ndef get_rand_letter(type):\n\tif type == 'all':\n\t\tx = random.random() * 26\n\t\txmod = x % 1\n\t\tselect = int(x-xmod)\n\t\tall_letters = freq\n\t\tselection = all_letters[select]\n\t\t\n\tif type == 'vow':\n\t\tx = random.random() * 5\n\t\txmod = x % 1\n\t\tselect = int(x-xmod)\n\t\tselection = lib_vowels[select]\n\t\t\n\tif type == 'cons':\n\n\t\tx = random.random() * 21\n\t\txmod = x % 1\n\t\tselect = int(x-xmod)\n\t\tselection = cons[select]\n\treturn selection\n\nif __name__ == '__main__':\n\tget_rand_letter(type)","sub_path":"hist/hist4/prod/lib/get_rand_letter.py","file_name":"get_rand_letter.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"311444048","text":"\n\n#calss header\nclass _EYESTRAIN():\n\tdef __init__(self,): \n\t\tself.name = \"EYESTRAIN\"\n\t\tself.definitions = [u'tired or painful eyes as a result of too much reading, looking at a computer screen, etc.']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_eyestrain.py","file_name":"_eyestrain.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"152551275","text":"antall_kvinner = 0\nantall_menn = 0\nantall_fag = 0\nantall_itgk = 0\nantall_timer_lekser = 0\n\nkjønn = 0\nage = 0\nfag = 0\n#hvis noen sier hade så vil while løkken avsluttes.\n\ndef whilekjonn():\n kjønn = input(\"Er du mann eller kvinne?\\n\").lower()\n if kjønn == \"m\" or kjønn == \"mann\" or kjønn == \"k\" or kjønn == \"kvinne\" or kjønn == \"hade\":\n return kjønn\n else:\n print (\"Ugyldig kjønn\")\n whilekjonn()\n\ndef alder():\n age = int(input(\"Hvor gammel er du?\\n\"))\n return age\n\ndef fager():\n fag = input(\"Tar du ett fag?\\n\").lower()\n if fag == \"ja\" or fag == \"j\" or fag == \"nei\" or fag == \"n\":\n return fag\n else:\n print(\"Ugyldig svar\")\n fager()\n\ndef itgk(age):\n global antall_itgk\n antall_itgk += 1\n if age <= 22:\n print (\"Tar du ITGK?\")\n else:\n print (\"Tar du særr ITGK?\")\n\n\nwhile True:\n kjønn = whilekjonn()\n if kjønn == \"m\" or kjønn == \"mann\":\n print (\"Du er en mann\")\n antall_menn += 1\n elif kjønn == \"k\" or kjønn == \"kvinne\":\n print (\"Du er en kvinne\")\n antall_kvinner += 1\n elif kjønn == \"hade\":\n break\n\n age = alder()\n if 16 <= age <= 25:\n print(\"Du passer perf.\")\n fag = fager()\n if fag == \"ja\" or fag == \"j\":\n itgk(age)\n antall_fag += 1\n timer_lekser = float(input(\"Hvor mange timer i uka bruker du i uka på lekser da?\\n\"))\n antall_timer_lekser += timer_lekser\n\n elif fag == \"hade\":\n break\n else:\n print(\"Du burde ta ITGK.\")\n else:\n print(\"Du er ikke innenfor aldersgruppen vi søker, beklager\")\n\nprint(\"Kvinner {}, Menn {}, fag {}, itgk {}, timer lekser {}\".format(antall_kvinner, antall_menn, antall_fag, antall_itgk, antall_timer_lekser))\n","sub_path":"Øving 5/spørre.py","file_name":"spørre.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"591765509","text":"#!/usr/bin/env python3\n\ndef flips_needed(stack):\n flips = 0\n for i in range(len(stack) - 1):\n if stack[i] != stack[i + 1]:\n flips += 1\n if stack[-1] == '-':\n flips += 1\n return flips\n\nfor case_number in range(int(input())):\n print('Case #{}: {}'.format(case_number + 1, flips_needed(input())))\n","sub_path":"codes/CodeJamCrawler/16_0_2/afg/problem-b.py","file_name":"problem-b.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"418684099","text":"from api.app import app \nfrom api.app import mongo\nfrom flask import request,Response,jsonify\nfrom bson.json_util import loads, dumps, ObjectId\nimport json\n\n@app.route('/') #doy la bienvenida solo con la url original\ndef hola_mundo():\n return \"

BIENVENIDO A COBIFY!!!!

\"\n\n\n@app.route(\"/gas/\")\ndef gas_caracteristicas(tipo):\n #SACA LAS CARACTERISTICAS DE CADA TRAYECTO EN TORNO A ESE TIPO DE GAS\n tipo = mongo.db.combustibles.find({\"gas_type\":tipo})\n r = dumps(tipo)\n rjson = Response(r, mimetype=\"application/json\")\n return rjson\n\n#media de consumo de cada tipo de gas y el gasto\n\n@app.route(\"/consumo/\")\ndef consumo_medio(gas):\n consumo = mongo.db.combustibles.find({\"gas_type\":gas})\n \n l = list(consumo)\n lista = [i[\"consume\"]for i in l]\n consumo_medio = sum(lista)/len(lista)\n \n return {\"consumo_medio\": round(consumo_medio,2),\"gasto\": round(consumo_medio*l[1][\"price\"],2)}\n\n#consumo con lluvia o sin lluvia y gasto \n@app.route(\"/lluvia//\")\ndef lluvia(gas,numero):\n rain = mongo.db.combustibles.find({\"gas_type\":gas,\"rain\":numero})\n t = list(rain)\n lista_nueva = [i[\"consume\"] for i in t]\n \n\n \n med = sum(lista_nueva)/len(lista_nueva)\n return {\"consumo medio\": round(med,2), \"gasto\": round(med*t[1][\"price\"],2) }\n \n#lo mismo pero con el sol \n@app.route(\"/sol//\")\ndef sol(gas,numero):\n sol = mongo.db.combustibles.find({\"gas_type\":gas,\"sun\":numero})\n t = list(sol)\n lista_nueva = [i[\"consume\"] for i in t]\n med = sum(lista_nueva)/len(lista_nueva)\n return {\"consumo medio\": round(med,2), \"gasto\": round(med*t[1][\"price\"],2) }\n \n#Con AC o sin aire\n\n@app.route(\"/aire//\")\ndef aire(gas,numero):\n aire = mongo.db.combustibles.find({\"gas_type\":gas,\"AC\":numero})\n t = list(aire)\n lista_nueva = [i[\"consume\"] for i in t]\n med = sum(lista_nueva)/len(lista_nueva)\n return {\"consumo medio\": round(med,2), \"gasto\": round(med*t[1][\"price\"],2) }\n\n\n ","sub_path":"api/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"413510982","text":"import re\nimport os\nimport logging\nimport string\nfrom collections import defaultdict\nfrom urllib import quote\nfrom urlparse import urljoin\nfrom ConfigParser import RawConfigParser\nfrom pprint import pformat\n\nfrom tg import config\nfrom pylons import c, g, request\nfrom BeautifulSoup import BeautifulSoup\n\nimport markdown\nimport feedparser\n\nfrom . import macro\nfrom . import helpers as h\n\nlog = logging.getLogger(__name__)\n\nPLAINTEXT_BLOCK_RE = re.compile( \\\n r'(?P\\[plain\\])(?P.*?)(?P\\[\\/plain\\])',\n re.MULTILINE|re.DOTALL\n )\n\nclass ForgeExtension(markdown.Extension):\n\n def __init__(self, wiki=False, email=False, macro_context=None):\n markdown.Extension.__init__(self)\n self._use_wiki = wiki\n self._is_email = email\n self._macro_context = macro_context\n\n def extendMarkdown(self, md, md_globals):\n md.registerExtension(self)\n self.forge_processor = ForgeProcessor(self._use_wiki, md, macro_context=self._macro_context)\n self.forge_processor.install()\n md.preprocessors['fenced-code'] = FencedCodeProcessor()\n md.preprocessors.add('plain_text_block', PlainTextPreprocessor(md), \"_begin\")\n md.inlinePatterns['autolink_1'] = AutolinkPattern(r'(http(?:s?)://[a-zA-Z0-9./\\-_0%?&=+#;~:]+)')\n md.treeprocessors['br'] = LineOrientedTreeProcessor(md)\n # Sanitize HTML\n md.postprocessors['sanitize_html'] = HTMLSanitizer()\n # Rewrite all relative links that don't start with . to have a '../' prefix\n md.postprocessors['rewrite_relative_links'] = RelativeLinkRewriter(\n make_absolute=self._is_email)\n # Put a class around markdown content for custom css\n md.postprocessors['add_custom_class'] = AddCustomClass()\n md.postprocessors['mark_safe'] = MarkAsSafe()\n\n def reset(self):\n self.forge_processor.reset()\n\nclass PlainTextPreprocessor(markdown.preprocessors.Preprocessor):\n\n def run(self, lines):\n text = \"\\n\".join(lines)\n while 1:\n res = PLAINTEXT_BLOCK_RE.finditer(text)\n for m in res:\n code = self._escape(m.group('code'))\n placeholder = self.markdown.htmlStash.store(code, safe=True)\n text = '%s%s%s'% (text[:m.start()], placeholder, text[m.end():])\n break\n else:\n break\n return text.split(\"\\n\")\n\n def _escape(self, txt):\n \"\"\" basic html escaping \"\"\"\n txt = txt.replace('&', '&')\n txt = txt.replace('<', '<')\n txt = txt.replace('>', '>')\n txt = txt.replace('\"', '"')\n return txt\n\nclass FencedCodeProcessor(markdown.preprocessors.Preprocessor):\n pattern = '~~~~'\n\n def run(self, lines):\n in_block = False\n new_lines = []\n for line in lines:\n if line.lstrip().startswith(self.pattern):\n in_block = not in_block\n continue\n if in_block:\n new_lines.append(' ' + line)\n else:\n new_lines.append(line)\n return new_lines\n\nclass ForgeProcessor(object):\n alink_pattern = r'(?= len(stash): return ''\n return stash[id]\n\n def compile(self):\n from allura import model as M\n if self.stash['artifact'] or self.stash['link']:\n try:\n self.alinks = M.Shortlink.from_links(*self.stash['artifact'])\n self.alinks.update(M.Shortlink.from_links(*self.stash['link']))\n except:\n self.alinks = {}\n self.stash['artifact'] = map(self._expand_alink, self.stash['artifact'])\n self.stash['link'] = map(self._expand_link, self.stash['link'])\n self.stash['macro'] = map(macro.parse(self._macro_context), self.stash['macro'])\n\n def reset(self):\n self.stash = dict(\n artifact=[],\n macro=[],\n link=[])\n self.alinks = {}\n self.compiled = False\n\n def _expand_alink(self, link):\n new_link = self.alinks.get(link, None)\n if new_link:\n return '[%s]' % (\n new_link.url, link)\n elif self._use_wiki and ':' not in link:\n return '[%s]' % (\n h.urlquote(link), link)\n else:\n return link\n\n def _expand_link(self, link):\n reference = self.alinks.get(link)\n mailto = u'\\x02amp\\x03#109;\\x02amp\\x03#97;\\x02amp\\x03#105;\\x02amp\\x03#108;\\x02amp\\x03#116;\\x02amp\\x03#111;\\x02amp\\x03#58;'\n if not reference and not link.startswith(mailto) and '#' not in link:\n return 'notfound'\n else:\n return ''\n\nclass ForgeInlinePattern(markdown.inlinepatterns.Pattern):\n\n def __init__(self, parent, pattern):\n self.parent = parent\n markdown.inlinepatterns.Pattern.__init__(\n self, pattern, parent.markdown)\n\n def handleMatch(self, m):\n return self.parent.store(m.group(2))\n\nclass ForgePostprocessor(markdown.postprocessors.Postprocessor):\n\n def __init__(self, parent):\n self.parent = parent\n markdown.postprocessors.Postprocessor.__init__(\n self, parent.markdown)\n\n def run(self, text):\n self.parent.compile()\n def repl(mo):\n return self.parent.lookup(mo.group(1), int(mo.group(2)))\n return self.parent.placeholder_re.sub(repl, text)\n\nclass ForgeTreeProcessor(markdown.treeprocessors.Treeprocessor):\n '''This flags intra-wiki links that point to non-existent pages'''\n\n def __init__(self, parent):\n self.parent = parent\n\n def run(self, root):\n for node in root.getiterator('a'):\n href = node.get('href')\n if not href: continue\n if '/' in href: continue\n classes = node.get('class', '').split() + [ self.parent._store('link', href) ]\n node.attrib['class'] = ' '.join(classes)\n return root\n\nclass MarkAsSafe(markdown.postprocessors.Postprocessor):\n\n def run(self, text):\n return h.html.literal(text)\n\nclass AddCustomClass(markdown.postprocessors.Postprocessor):\n\n def run(self, text):\n return '
%s
' % text\n\nclass RelativeLinkRewriter(markdown.postprocessors.Postprocessor):\n\n def __init__(self, make_absolute=False):\n self._make_absolute = make_absolute\n\n def run(self, text):\n try:\n if not request.path_info.endswith('/'): return text\n except:\n # Must be being called outside the request context\n pass\n soup = BeautifulSoup(text)\n if self._make_absolute:\n rewrite = self._rewrite_abs\n else:\n rewrite = self._rewrite\n for link in soup.findAll('a'):\n rewrite(link, 'href')\n for link in soup.findAll('img'):\n rewrite(link, 'src')\n return unicode(soup)\n\n def _rewrite(self, tag, attr):\n val = tag.get(attr)\n if val is None: return\n if ' ' in val:\n # Don't urllib.quote to avoid possible double-quoting\n # just make sure no spaces\n val = val.replace(' ', '%20')\n tag[attr] = val\n if '://' in val:\n if 'sf.net' in val or 'sourceforge.net' in val:\n return\n else:\n tag['rel']='nofollow'\n return\n if val.startswith('/'): return\n if val.startswith('.'): return\n if val.startswith('mailto:'): return\n if val.startswith('#'): return\n tag[attr] = '../' + val\n\n def _rewrite_abs(self, tag, attr):\n self._rewrite(tag, attr)\n val = tag.get(attr)\n val = urljoin(config.get('base_url', 'http://sourceforge.net/'),val)\n tag[attr] = val\n\nclass HTMLSanitizer(markdown.postprocessors.Postprocessor):\n\n def run(self, text):\n try:\n p = feedparser._HTMLSanitizer('utf-8')\n except TypeError: # $@%## pre-released versions from SOG\n p = feedparser._HTMLSanitizer('utf-8', '')\n p.feed(text.encode('utf-8'))\n return unicode(p.output(), 'utf-8')\n\nclass LineOrientedTreeProcessor(markdown.treeprocessors.Treeprocessor):\n '''Once MD is satisfied with the etree, this runs to replace \\n with
\n within

s.\n '''\n\n def __init__(self, md):\n self._markdown = md\n \n def run(self, root):\n for node in root.getiterator('p'):\n if not node.text: continue\n if '\\n' not in node.text: continue\n text = self._markdown.serializer(node)\n text = self._markdown.postprocessors['raw_html'].run(text)\n text = text.strip().encode('utf-8')\n if '\\n' not in text: continue\n new_text = (text\n .replace('
', '
')\n .replace('\\n', '
'))\n new_node = None\n try:\n new_node = markdown.etree.fromstring(new_text)\n except SyntaxError:\n try:\n new_node = markdown.etree.fromstring(unicode(BeautifulSoup(new_text)))\n except:\n log.exception('Error adding
tags: new text is %s', new_text)\n pass\n if new_node:\n node.clear()\n node.text = new_node.text\n node[:] = list(new_node)\n return root\n\nclass AutolinkPattern(markdown.inlinepatterns.LinkPattern):\n\n def handleMatch(self, mo):\n old_link = mo.group(2)\n result = markdown.etree.Element('a')\n result.text = old_link\n result.set('href', old_link)\n return result\n\n","sub_path":"Allura/allura/lib/markdown_extensions.py","file_name":"markdown_extensions.py","file_ext":"py","file_size_in_byte":11415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"468581628","text":"from standalone import pddl\nfrom standalone import statistics\n\nfrom standalone.task import PlanningStatusEnum, Task\nimport standalone.globals as global_vars\n\nfrom standalone import config\nlog = config.logger(\"mapsim\")\n\nstatistics_defaults = dict(\n execution_time=0.0,\n failed_execution_attempts=0,\n physical_actions_executed=0,\n sensor_actions_executed=0,\n speech_acts_executed=0,\n total_plan_cost=0,\n reward=0\n )\n\n\ntask_id = 0\ndef next_id():\n global task_id\n task_id += 1\n return task_id-1\n\ndef loggingScope(f):\n def new_f(self, *args, **kwargs):\n oldscope = config.logfile_scope\n if global_vars.mapsim_config.separate_logs:\n config.logfile_scope = self.name\n rval = f(self, *args, **kwargs)\n config.logfile_scope = oldscope\n return rval\n \n new_f.__name__ = f.__name__\n return new_f\n\nclass BaseAgent(object):\n def __init__(self, simulator):\n self.simulator = simulator\n self.running = False\n\n def run(self):\n self.running = True\n \n def execute(self, action, args):\n self.simulator.schedule(action, args, self)\n\n def done(self):\n self.running = False\n self.simulator.signal_done(self)\n\n def is_running(self):\n return self.running\n\n\nclass Agent(BaseAgent):\n def __init__(self, name, mapltask, planner, simulator):\n BaseAgent.__init__(self, simulator)\n \n self.name = name\n self.planner = planner\n self.statistics = statistics.Statistics(defaults = statistics_defaults)\n self.last_action = None\n\n self.new_task(mapltask)\n\n def get_state(self):\n return self.task.get_state()\n\n def update_state(self, svar, val):\n self.get_state()[svar] = val\n\n def new_task(self, mapltask):\n self.mapltask = mapltask.copy()\n\n prob_state = pddl.prob_state.ProbabilisticState.from_problem(self.mapltask)\n state = prob_state.determinized_state(0.1, 0.9)\n \n if global_vars.mapsim_config.add_assertions:\n self.task = Task(next_id(), self.mapltask, add_assertions=True)\n self.task.set_state(state)\n else:\n self.task = Task(next_id(), self.mapltask)\n self.task.set_state(state)\n \n self.planner.register_task(self.task)\n\n @loggingScope\n def run(self):\n BaseAgent.run(self)\n self.task.replan()\n self.execute_plan(self.task)\n\n def write_plan(self, plan):\n if global_vars.mapsim_config.write_dotfiles:\n G = plan.to_dot()\n G.write(\"plan.dot\")\n if global_vars.mapsim_config.write_pdffiles:\n G = plan.to_dot() # a bug in pygraphviz causes write() to delete all node attributes when using subgraphs. So create a new graph.\n G.layout(prog='dot')\n G.draw(\"plan.pdf\")\n \n \n @loggingScope\n @statistics.time_method_for_statistics(\"execution_time\")\n def execute_plan(self, task):\n if task.planning_status == PlanningStatusEnum.PLANNING_FAILURE:\n return\n\n def action_cmp(pnode1, pnode2):\n if pnode1.action.is_pure_sensor() and not pnode2.action.is_pure_sensor():\n return -1\n elif not pnode1.action.is_pure_sensor() and pnode2.action.is_pure_sensor():\n return 1\n\n for s1, s2 in [(pnode1.action.name, pnode2.action.name)] + zip(map(str, pnode1.args), map(str, pnode2.args)):\n if cmp(s1, s2) != 0:\n return cmp(s1, s2)\n return 0\n \n plan = task.get_plan()\n self.write_plan(plan)\n #all_funcs = set(self.mapltask.functions) | set(self.mapltask.predicates)\n # print \"instantiate:\"\n #mapl.sas_translate.to_sas(self.mapltask)\n # print \"executable:\"\n # for a in self.mapltask.actions:\n # a = pddl.mapl.MAPLObjectFluentNormalizer().translate(a, domain=self.mapltask)\n \n # for c in pddl.sas_translate.instantiate_action(a, task.get_state(), all_funcs):\n # print \"(%s %s)\" % (a.name, \" \".join(o.name for o in c))\n\n executable = sorted(plan.executable(), cmp=action_cmp)\n log.info(\"executable actions: %s\", \" \".join(map(str, executable)))\n if executable:\n log.debug(\"trying to execute (%s %s)\", executable[0].action.name, \" \".join(map(str, executable[0].args)))\n self.last_action = executable[0]\n self.execute(executable[0].action.name, executable[0].full_args)\n else:\n log.debug(\"nothing more to do.\")\n self.done()\n\n \n @loggingScope\n def updateTask(self, new_facts, action_status=None):\n plan = self.task.get_plan()\n\n if plan is not None and action_status:\n self.last_action.status = action_status\n \n for f in new_facts:\n self.task.get_state().set(f)\n \n self.task.mark_changed()\n self.task.replan()\n self.execute_plan(self.task)\n\n def collect_statistics(self):\n \"\"\" return all stats collected by this agent (usually to the simulation) \"\"\"\n return self.statistics.merge(self.task.statistics)\n","sub_path":"subarchitectures/planner.sa/branches/surprises/src/python/mapsim/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502056742","text":"# ----------------------------------------------------------\n# Introdução a Programação de Computadores - IPC\n# Universidade do Estado do Amazonas - UEA\n# Prof. Jucimar Jr\n# tiago ferreira aranha \t 1715310047\n# Luiz Daniel Raposo Nunes de Mello\t 1715310049\n# Gabriel nascimento de Oliveira 1715310052\n# Wilbert Luís Evangelista Marins 1715310055\n# Mackson Garcez Moreno de Oliveira júnior 1215090300\n# Edson de Lima Barros 1715310043\n#\n# 5. Desenhar uma estrela de 5 pontas\n# ----------------------------------------------------------\n\nimport turtle\nlados = 10\n\np = turtle.Pen()\n\nfor x in range(lados):\n p.forward(50)\n p.left(360/lados)\n p.forward(50)\n p.right(360/lados*2)\n\n\n\nturtle.mainloop()\n","sub_path":"lista02/lista02_exercicio05.py","file_name":"lista02_exercicio05.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162663535","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.forum, name='forum'),\n\turl(r'^block/(?P\\d+)/$', views.block, name='block'),\n\turl(r'^check/', views.checking, name='check'),\n\turl(r'^post/(?P\\d+)/$', views.post_detail, name='forum_post_detail'),\n\turl(r'^post/add/(?P\\d+)/$', views.post_add, name='forum_post_add'),\n\turl(r'^ajax/post_freeze$', views.close, name='post_freeze'),\n\turl(r'^ajax/post_check$', views.check, name='post_check'),\n\turl(r'^ajax/post_delete$', views.delete, name='post_delete'),\n]","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"434225341","text":"# use something with NLTK enabled\n\nimport nltk\nfrom response import *\n\nfd = open(\"pos-nouns\", \"r\")\nposSubjects=fd.read().splitlines()\nfd.close()\nfd = open(\"neg-nouns\", \"r\")\nnegSubjects=fd.read().splitlines()\nfd.close\n\nprint(\"Welcome to your interview with Pres. Trump. Please keep your questions simple.\")\n\nwhile True:\n\tsentence = input(\"> \")\n\n\t# hey, that's a common use case, might as well make it work\n\tif sentence.casefold() in [\"hello\",\"hi\"] :\n\t\tprint(sayHello())\n\t\tcontinue\n\t\t\n\tif sentence.casefold().startswith(\"bye\"):\n\t\tprint(sayBye())\n\t\tbreak\n\n\ttokens = nltk.word_tokenize(sentence)\n\ttagged = nltk.tag.pos_tag(tokens)\n\t\n\t# trees are too complicated for now\n\t\"\"\"\n\ttaggedStr=\"(\"\n\tfor i in tagged:\n\t\ttaggedStr+=str(i)\n\ttaggedStr+=\")\"\n\t\n\tsenTree = nltk.tree.Tree.fromstring(taggedStr)\n\t\n\tsenTree.subtrees()\n\t#print(senTree)\n\t\"\"\"\n\t# we try to find a proper noun (NNP) to talk about. If we can't, we take an noun (NN)\n\t\n\tsubject=\"none\"\n\t\n\t# it would be very interesting to analyse a corpus of trump's speech to get a list of negative or positive terms\n\t#negSubjects=[\"democrats\", \"obama\", \"clinton\", \"mccain\", \"cnn\", \"taxes\", \"obamacare\", \"ACA\"]\n\t#posSubjects=[\"ivanka\", \"bannon\", \"kushner\", \"breitbart\", \"fox\", \"nuclear\", \"rich\", \"science\", \"guns\"]\n\n\t# this should do AS LONG AS WE DO NOT HAVE COMPLEX SENTENCES\n\tfor i in tagged:\n\t\tif i[1] == \"NNP\":\n\t\t\tsubject=i\n\tif subject == \"none\":\n\t\tfor i in tagged:\n\t\t\tif i[1] == \"NN\" or i[1] == \"NNS\":\n\t\t\t\tsubject=i\n\t\n\t\n\tif subject==\"none\":\n\t\tprint(rambling())\n\t# the way we generate our pos/neg nouns mean they can appear in both positive and negative lists. Currently, we just favor the negative.\n\telif subject[0].casefold() in negSubjects:\n\t\tprint(negativeResponse(subject[0], subject[1]))\n\telif subject[0].casefold() in posSubjects:\n\t\t#positive response\n\t\tprint(positiveResponse(subject[0], subject[1]))\n\telse:\n\t\t#neutral response\n\t\tprint(neutralResponse(subject[0], subject[1]))\n\t\n\t# now we have the subject, we should work on getting a rough \"sentence type\", to know what type of answer we need to give.\n\t\n\t#print(\"I'm too intelligent for this.\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"221897425","text":"\"\"\"\nMIT License\nCopyright (c) 2020 GamingGeek\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\nFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nfrom logging.handlers import TimedRotatingFileHandler\nfrom jishaku.modules import resolve_extensions\nimport core.coloredformat as colorformat\nfrom discord.ext import commands, tasks\nfrom aioinflux import InfluxDBClient\nfrom sentry_sdk import push_scope\nfrom .context import Context\nfrom .config import Config\nimport functools\nimport traceback\nimport sentry_sdk\nimport aiofiles\nimport aiohttp\nimport datetime\nimport discord\nimport asyncpg\nimport logging\nimport typing\nimport json\nimport sys\n\n\nclass Fire(commands.Bot):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.launchtime = datetime.datetime.utcnow()\n\n # COMMON ATTRIBUTES\n self.config: dict = json.load(open('config.json', 'r'))\n self.configs = {}\n self.overrides: dict = json.load(open('overrides.json', 'r'))\n self.override_save.start()\n self.tips = json.load(open('tips.json', 'r'))\n self.premiumGuilds = []\n self.db: asyncpg.pool.Pool = None\n self.realtime_members = True\n self.dev = kwargs.pop('dev', False)\n\n # CRAB\n self.crab = '🦀'\n\n # LOGGING\n logging.basicConfig(filename='bot.log', level=logging.INFO)\n self.logger = logging.getLogger('Fire')\n stdout = logging.StreamHandler(sys.stdout)\n stdout.setLevel(logging.INFO)\n COLOR_FORMAT = colorformat.formatter_message(\"[$BOLD%(name)s$RESET][%(levelname)s] %(message)s $RESET($BOLD%(filename)s$RESET:%(lineno)d)\")\n stdout.setFormatter(colorformat.ColoredFormatter(COLOR_FORMAT))\n self.logger.addHandler(stdout)\n\n # SENTRY\n if 'sentry' in self.config:\n sentry_sdk.init(self.config['sentry'])\n\n # INFLUX\n if 'influx_user' in self.config and 'influx_pass' in self.config:\n self.influx = InfluxDBClient(\n db='firedev' if self.dev else 'fire',\n username=self.config['influx_user'],\n password=self.config['influx_pass']\n )\n\n # MODULES\n self.load_modules()\n\n # COMMANDS\n self.load_commands()\n self.cmdresp = {}\n\n # EVENTS\n self.load_events()\n\n # CUSTOM PERMISSIONS\n # self.permissions = {}\n\n async def get_context(self, message: discord.Message, **kwargs):\n silent = False\n if message.content and message.content.endswith(' --silent'):\n message.content = message.content[:-9]\n silent = True\n if 'cls' not in kwargs:\n ctx = await super().get_context(message, cls=Context, **kwargs)\n else:\n ctx = await super().get_context(message, **kwargs)\n if ctx.valid and silent:\n try:\n await message.delete()\n except Exception:\n pass\n return ctx\n\n def get_message(self, mid: int):\n if not self.cached_messages:\n return None\n found = [m for m in self.cached_messages if m.id == mid]\n if not found:\n return None\n return found[0]\n\n def isadmin(self, user: typing.Union[discord.User, discord.Member]) -> bool:\n if str(user.id) not in self.config['admins']:\n admin = False\n else:\n admin = True\n return admin\n\n def load_commands(self):\n try:\n # raise Exception('Chatwatch is temporarily disabled')\n self.load_extension('core.chatwatch')\n except Exception as e:\n # errortb = ''.join(traceback.format_exception(\n # type(e), e, e.__traceback__))\n self.logger.error(f'$REDError while loading $CYANChatwatch', exc_info=e)\n try:\n self.load_extension('jishaku')\n except Exception as e:\n # errortb = ''.join(traceback.format_exception(\n # type(e), e, e.__traceback__))\n self.logger.error(f'$REDError while loading $CYANJishaku', exc_info=e)\n for ext in resolve_extensions(self, 'commands.*'):\n try:\n self.load_extension(ext)\n except Exception as e:\n # errortb = ''.join(traceback.format_exception(\n # type(e), e, e.__traceback__))\n self.logger.error(f'$REDError while loading $CYAN{ext}', exc_info=e)\n\n def load_events(self):\n for ext in resolve_extensions(self, 'events.*'):\n try:\n self.load_extension(ext)\n except Exception as e:\n # errortb = ''.join(traceback.format_exception(\n # type(e), e, e.__traceback__))\n self.logger.error(f'$REDError while loading {ext}', exc_info=e)\n\n def load_modules(self):\n for ext in resolve_extensions(self, 'modules.*'):\n try:\n self.load_extension(ext)\n except Exception as e:\n # errortb = ''.join(traceback.format_exception(\n # type(e), e, e.__traceback__))\n self.logger.error(f'$REDError while loading {ext}', exc_info=e)\n\n def sentry_exc(self, error: commands.CommandError, userscope: dict, exclevel: str, extra: dict):\n with push_scope() as scope:\n scope.user = userscope\n scope.level = exclevel\n for key in extra:\n scope.set_tag(key, extra[key])\n sentry_sdk.capture_exception(error)\n\n @tasks.loop(minutes=2)\n async def override_save(self):\n await self.wait_until_ready()\n try:\n f = await aiofiles.open('overrides.json', 'w')\n await f.write(json.dumps(self.overrides))\n await f.close()\n except Exception:\n pass\n\n async def haste(self, content, fallback: bool=False):\n url = 'hst.sh'\n if fallback:\n url = 'h.inv.wtf'\n async with aiohttp.ClientSession().post(f'https://{url}/documents', data=content) as r:\n if r.status != 200 and not fallback:\n return await self.haste(content, fallback=True)\n j = await r.json()\n return f'https://{url}/' + j['key']\n\n async def is_team_owner(self, user: typing.Union[discord.User, discord.Member]):\n if user.id == self.owner_id:\n return True\n else:\n return False\n","sub_path":"core/fire.py","file_name":"fire.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619105178","text":"from django.shortcuts import render, redirect\r\nfrom . import models\r\nimport datetime\r\n# Create your views here.\r\n\r\n\r\ndef index(request):\r\n boardList = models.Board.objects.all()\r\n return render(request, 'board/index.html', {'boards': boardList})\r\n\r\n\r\ndef submit(request):\r\n name = request.POST.get('name')\r\n content = request.POST.get('content')\r\n date = str(datetime.datetime.now())\r\n new_board = models.Board(name=name, content=content, date=date)\r\n new_board.save()\r\n return redirect('/index')\r\n","sub_path":"每天练习/0023/message/board/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"552945745","text":"import pandas as pd\n#from decimal import Decimal\nteamDF = pd.read_csv('BBLTeams.csv')\nbatDF = pd.read_csv('BattingData.csv')\n#print(batDF)\nbowlDF = pd.read_csv('BowlingData.csv')\n\nbowlDF.set_index('Name', inplace = 'true')\nbatDF.set_index('Name', inplace = 'true')\nteamDF = teamDF.values\n\n#Teams\n#Adelaide Strikers\n#Brisbane Heat\n#Hobart Hurricanes\n#Melbourne Renegades\n#Melbourne Stars\n#Perth Scorchers\n#Sydney Sixers\n#Sydney Thunder\n\n#Team1 = -1\n#Team2 = -1\nBowlStat1 = 0\nBatStat1 = 0\nBowlStat2 = 0\nBatStat2 = 0\nTeam1 = -1\nTeam2 = -1\nwhile Team1 == -1:\n Team1 = input('Input home team: ')\n if Team1 == 'A':\n Team1 = 0\n elif Team1 == 'B':\n Team1 = 1\n elif Team1 == 'H':\n Team1 = 2\n elif Team1 == 'MR':\n Team1 = 3\n elif Team1 == 'MS':\n Team1 = 4\n elif Team1 == 'P':\n Team1 = 5\n elif Team1 == 'SS':\n Team1 = 6\n elif Team1 == 'ST':\n Team1 = 7\n else :\n print('Invalid Team')\n Team1=-1\nplayersNotPlaying1 = []\nppName = '_'\nppTF = input('For Home Team are there any players that are not playing?')\nwhile ppTF == 'y' or ppTF == 'yes' or ppTF == 'YES' :\n ppName = input('Player full name : ')\n playersNotPlaying1.append(ppName)\n ppTF = input('Any more players not playing? ')\n \n\n \n \n\nwhile Team2 == -1:\n Team2 = input('Away Team: ')\n if Team2 == 'A':\n Team2 = 0\n elif Team2 == 'B':\n Team2 = 1\n elif Team2 == 'H':\n Team2 = 2\n elif Team2 == 'MR':\n Team2 = 3\n elif Team2 == 'MS':\n Team2 = 4\n elif Team2 == 'P':\n Team2 = 5\n elif Team2 == 'SS':\n Team2 = 6\n elif Team2 == 'ST':\n Team2 = 7\n else :\n print('Invalid Team')\n Team2=-1\nplayersNotPlaying2 = []\nppName = '_'\nppTF = input('For Away Team are there any players that are not playing?')\nwhile ppTF == 'y' or ppTF == 'yes' or ppTF == 'YES' :\n ppName = input('Player full name : ')\n playersNotPlaying2.append(ppName)\n ppTF = input('Any more players not playing? ')\ncount2 = 0\nbowlCount1 = 0\nbatCount1 = 0\nbowlCount2 = 0\nbatCount2 = 0\n#home team calc\nwhile count2 <19:\n #print (row)\n #print(Team1)\n #print(teamDF.loc[:Team1])\n row1 = teamDF[count2,Team1]\n #row1 = row[Team1]#.strip('.')\n \n #print(row1)\n if count2 == 0:\n row2 = row1.rstrip(' (Captain)')\n else :\n row2 = row1\n print(row2)\n #print(row2 in bowlDF.index)\n if row2 not in playersNotPlaying1:\n if row2 in bowlDF.index :\n #BowlStat1 = float(BowlStat1) + float(bowlDF.loc[row2,'Ave'])*float(bowlDF.loc[row2,'Econ'])\n #insert bowl annalysis\n #print(type(bowlDF.loc[row2,'Ave']))\n bowlCount1 += 1\n if isinstance(bowlDF.loc[row2,'Ave'],str):\n try :\n BowlStat1 += float(bowlDF.loc[row2,'Ave'])*float(bowlDF.loc[row2,'Econ'])\n except:\n bowlCount1 = bowlCount1\n #print(float(bowlDF.loc[row2,'Ave'])*float(bowlDF.loc[row2,'Econ']))\n else :\n #print(float(bowlDF.loc[row2,'Ave'].values[0])*float(bowlDF.loc[row2,'Econ'].values[0]))\n BowlStat1 += float(bowlDF.loc[row2,'Ave'].values[0])*float(bowlDF.loc[row2,'Econ'].values[0])\n #AdeSix.loc[row1] = bowlDF.loc[row2]\n print('Bowl Stats :')\n print(BowlStat1)\n if row2 in batDF.index:\n # #insert bat annalysis\n #print('true')\n #print(type(batDF.loc[row2,'Ave'])) \n batCount1 += 1\n BatStat1 += batDF.loc[row2,'Ave']*batDF.loc[row2,'SR']\n print('Bat Stats: ')\n print(BatStat1)\n #print(BatStat1)\n # if isinstance(batDF.loc[row2,'Ave'],str):\n # \n # print(float(batDF.loc[row2,'Ave'])*float(batDF.loc[row2,'SR']))\n # BatStat1 += float(batDF.loc[row2,'Ave'])*float(batDF.loc[row2,'SR'])\n # else :\n # print(float(batDF.loc[row2,'Ave'].values[0])*float(batDF.loc[row2,'SR'].values[0]))\n # BatStat1 += float(batDF.loc[row2,'Ave'].values[0])*float(batDF.loc[row2,'SR'].values[0])\n #BatStat1 += batDF.loc[row2,'Ave']*batDF.loc[row2,'SR']\n count2 +=1\n \n \ncount2 = 0 \n#away team calc \nwhile count2 <19:\n row1 = teamDF[count2,Team2]\n if count2 == 0:\n row2 = row1.rstrip(' (Captain)')\n else :\n row2 = row1\n print(row2)\n if row2 not in playersNotPlaying2:\n if row2 in bowlDF.index :\n bowlCount2 += 1\n if isinstance(bowlDF.loc[row2,'Ave'],str):\n try :\n BowlStat2 += float(bowlDF.loc[row2,'Ave'])*float(bowlDF.loc[row2,'Econ'])\n except:\n bowlCount2 = bowlCount2\n else :\n BowlStat2 += float(bowlDF.loc[row2,'Ave'].values[0])*float(bowlDF.loc[row2,'Econ'].values[0])\n print('Bowl Stats :')\n print(BowlStat2)\n if row2 in batDF.index:\n batCount2 += 1\n BatStat2 += batDF.loc[row2,'Ave']*batDF.loc[row2,'SR']\n print('Bat Stats: ')\n print(BatStat2)\n count2 +=1\nBowlStat1 = BowlStat1/bowlCount1\nBatStat1 = BatStat1/batCount1\nBowlStat2 = BowlStat2/bowlCount2\nBatStat2 = BatStat2/batCount2\nprint(BowlStat1)\nprint(BatStat1)\nprint(BowlStat2)\nprint(BatStat2)\nprint(BowlStat2 * BatStat1)\nprint(BowlStat1 * BatStat2)\nHome = (45.5,38.1,50.0,66.67,40.91,62.5,46.45,18.18)\nAway = (57.14,52.17,43.48,64.0,52.38,60.87,53.55,31.82)\nif Home[Team1] < Away[Team2]:\n adjust = (Away[Team2] - Home[Team1])/100 + 1\n result = (BowlStat2 * BatStat1)/(adjust) - (BowlStat1 * BatStat2*adjust)\nelse :\n adjust = (Home[Team1] - Away[Team2])/100 + 1\n result = (BowlStat2 * BatStat1*adjust) - (BowlStat1 * BatStat2)/adjust\n###enter in adjust part\nprint('result is: ')\nprint(result)\nprint(playersNotPlaying1)\nprint('Team Two')\nprint(playersNotPlaying2)","sub_path":"Testing.py","file_name":"Testing.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"303729759","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom django_redis import get_redis_connection\nfrom django.utils import timezone\nfrom django.db import transaction\nfrom apps.users.models import Address\nfrom apps.goods.models import SKU\nimport json\n\nfrom .models import OrderInfo,OrderGoods\n\nfrom decimal import Decimal\n# Create your views here.\n\n\n\n\n\nclass OrderSettlementView(View):\n\n def get(self,request):\n user = request.user\n\n try:\n addresses = Address.objects.filter(user=request.user,is_deleted=False)\n except Exception as e:\n addresses = None\n\n conn = get_redis_connection('carts')\n item_dict = conn.hgetall(f'carts_{user.id}')\n cart_selected = conn.smembers(f'selected_{user.id}')\n cart = {}\n for sku_id in cart_selected:\n cart[int(sku_id)] = int(item_dict[sku_id])\n\n sku_list = []\n\n skus = SKU.objects.filter(id__in=cart.keys())\n for sku in skus:\n sku_list.append({\n 'id':sku.id,\n 'name':sku.name,\n 'default_image_url':sku.default_image_url,\n 'count': cart[sku.id],\n 'price':sku.price\n })\n\n freight = Decimal('10.00')\n\n list = []\n for address in addresses:\n list.append({\n 'id':address.id,\n 'province':address.province.name,\n 'city':address.city.name,\n 'district':address.district.name,\n 'place':address.place,\n 'receiver':address.receiver,\n 'mobile':address.mobile\n })\n\n context = {\n 'addresses':list,\n 'skus':sku_list,\n 'freight':freight,\n }\n\n return JsonResponse({'code':0,'errmsg':'ok','context':context})\n\n\nclass OrderCommitView(View):\n\n def post(self,request):\n json_dict = json.loads(request.body.decode())\n address_id = json_dict.get('address_id')\n pay_method = json_dict.get('pay_method')\n\n if not all([address_id,pay_method]):\n return JsonResponse({'code':400,'errmsg':'缺少必传参数'})\n try:\n address = Address.objects.get(id=address_id)\n except Exception as e:\n return JsonResponse({'code':400,'errmsg':'参数address_id有误'})\n\n if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'],OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:\n return JsonResponse({'code':400,'errmsg':'参数pay_method'})\n\n user = request.user\n\n order_id = timezone.localtime().strftime('%Y%m%H%M%S') + ('{:0>9d}'.format(user.id))\n\n\n with transaction.atomic():\n save_id = transaction.savepoint()\n\n\n order = OrderInfo.objects.create(\n order_id = order_id,\n user = user,\n address = address,\n total_count = 0,\n total_amount = Decimal('10.00'),\n freight = Decimal('0'),\n pay_method=pay_method,\n status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']\n if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']\n else OrderInfo.ORDER_STATUS_ENUM['UNSEND']\n )\n\n conn = get_redis_connection('carts')\n item_dict = conn.hgetall(f'carts_{user.id}')\n cart_selected = conn.smembers(f'selected_{user.id}')\n carts = {}\n for sku_id in cart_selected:\n carts[int(sku_id)] = int(item_dict[sku_id])\n\n sku_ids = carts.keys()\n\n\n for sku_id in sku_ids:\n sku = SKU.objects.get(id=sku_id)\n sku_count = carts[sku.id]\n if sku_count>sku.stock:\n return JsonResponse({'code':400,'errmsg':'库存不足'})\n\n sku.stock -= sku_count\n sku.sales += sku_count\n sku.save()\n\n OrderGoods.objects.create(\n order = order,\n sku=sku,\n count = sku_count,\n price=sku.price,\n )\n\n order.total_count += sku_count\n order.total_amount += (sku_count* sku.price)\n\n order.total_amount += order.freight\n order.save()\n\n transaction.savepoint_commit(save_id)\n\n\n pl = conn.pipeline()\n pl.hdel(f'carts_{user.id}',*cart_selected)\n pl.srem(f'selected_{user.id}',*cart_selected)\n pl.execute()\n\n return JsonResponse({'code':0,'errmsg':'ok','order_id':order.order_id})\n\n\n\n\n\n","sub_path":"meiduo_mall/apps/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"543279990","text":"if __name__ == '__main__':\n N = int(raw_input())\n l=[]\n y = \",\"\n for x in range(N):\n s= raw_input().split()\n value = s[0]\n value1= s[1:]\n if value!=\"print\":\n value+=\"(\"+y.join(value1)+\")\"\n eval(\"l.\"+value)\n else:\n print(l)\n","sub_path":"Programs/Basic Data Types/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"319582086","text":"\"\"\"\nBackground\n\nThe Genomics program requires stable research IDs (RIDs). This is a script that will\nadd only pid/rid mappings for participants that don't currently exist in the\nprimary pid_rid_mapping table.\n\nThese records will be appended to the pipeline_tables.pid_rid_mapping table in BigQuery.\nDuplicate mappings are not allowed.\n\"\"\"\n# Python imports\nimport argparse\nimport inspect\nimport logging\nimport time\n\n# Third party imports\nfrom google.cloud import bigquery\n\n# Project imports\nfrom common import (JINJA_ENV, MAX_DEID_DATE_SHIFT, PID_RID_MAPPING,\n PIPELINE_TABLES)\nfrom utils import auth, bq\n\nLOGGER = logging.getLogger(__name__)\n\nSCOPES = [\n 'https://www.googleapis.com/auth/bigquery',\n 'https://www.googleapis.com/auth/devstorage.read_write',\n]\n\nGET_NEW_MAPPINGS = JINJA_ENV.from_string(\"\"\"\nINSERT INTO `{{primary.project}}.{{primary.dataset_id}}.{{primary.table_id}}`\n(person_id, research_id, shift)\nSELECT\n person_id\n , research_id\n-- generates random shifts between 1 and max_shift inclusive --\n , CAST(FLOOR({{max_shift}} * RAND() + 1) AS INT64) as shift\nFROM `{{rdr_table.project}}.{{rdr_table.dataset_id}}.{{rdr_table.table_id}}`\nWHERE person_id not in (\n SELECT person_id\n FROM `{{primary.project}}.{{primary.dataset_id}}.{{primary.table_id}}`)\n-- This is just to make sure we don't duplicate either person_id OR research_id --\nAND research_id not in (\n SELECT research_id\n FROM `{{primary.project}}.{{primary.dataset_id}}.{{primary.table_id}}`)\n\"\"\")\n\n\ndef store_to_primary_mapping_table(fq_rdr_mapping_table,\n client=None,\n run_as=None):\n \"\"\"\n Store the provided mappings and create required date shifts.\n\n Curation must maintain a stable pid/rid mapping for participants, as well\n as a date shift integer. Curation gets the pid/rid mapping table from the\n RDR team as part of their ETL process. Curation must identify new pid/rid\n mapping pairs, create random date shifts for each pair, and store the three\n tuple to the pipeline_tables.pid_rid_mapping table.\n\n This script requires either a client object be passed as a parameter or an\n email address to impersonate be provided. If both are missing, the script\n will not execute!\n\n The script assumes the newly provided mapping table exists in the same\n project as the primary mapping table.\n\n :param fq_rdr_mapping_table: a dot separated fully qualified name of the\n recently imported pid_rid_mapping table.\n :param client: a client object to use for querying both tables\n :param run_as: the email address of the service account to run as. if\n impersonation is already set up, pass the existing client object instead.\n\n :return: None\n :raises: RuntimeError if client and run_as are both None. BigQuery errors.\n \"\"\"\n project, dataset, table = fq_rdr_mapping_table.split('.')\n\n LOGGER.info(\n f'RDR mapping info: project -> {project}\\tdataset -> {dataset}\\ttable -> {table}'\n )\n LOGGER.info(f'Primary mapping info: project -> {project}\\t'\n f'dataset -> {PIPELINE_TABLES}\\ttable -> {PID_RID_MAPPING}')\n\n if not client and not run_as:\n LOGGER.error('Run cannot proceed without proper credentials')\n raise RuntimeError(\n 'Provide either a client or a service account to impersonate.')\n\n # set up an impersonated client if one is not provided\n if not client:\n LOGGER.info(\n 'Using impersonation credentials and creating a new client.')\n # get credentials and create client\n impersonation_creds = auth.get_impersonation_credentials(run_as, SCOPES)\n\n client = bq.get_client(project, credentials=impersonation_creds)\n else:\n LOGGER.info('Client object provided and being used.')\n\n # rdr table ref\n dataset_ref = bigquery.DatasetReference(project, dataset)\n rdr_table = bigquery.TableReference(dataset_ref, table)\n\n # primary table ref\n dataset_ref = bigquery.DatasetReference(project, PIPELINE_TABLES)\n primary_mapping_table = bigquery.TableReference(dataset_ref,\n PID_RID_MAPPING)\n\n # Query job config\n labels = {\n 'rdr_mapping_table':\n '-'.join(fq_rdr_mapping_table.lower().split('.')[1:])[-63:],\n 'module_name':\n __file__.lower().replace('/', '-').replace('.', '-')[-63:]\n }\n\n job_prefix = inspect.currentframe().f_code.co_name\n query = GET_NEW_MAPPINGS.render(rdr_table=rdr_table,\n primary=primary_mapping_table,\n max_shift=MAX_DEID_DATE_SHIFT)\n\n LOGGER.info(f'Preparing to run query:\\n{query}')\n\n config = bigquery.job.QueryJobConfig(labels=labels)\n\n new_mappings_job = client.query(query,\n job_config=config,\n job_id_prefix=job_prefix)\n\n # wait for the query to finish\n LOGGER.info('Waiting for pid/rid/shift storage query to finish.')\n new_mappings_job.result()\n LOGGER.info('Query has finished.')\n\n LOGGER.info(f'{new_mappings_job.num_dml_affected_rows} mapping records '\n f'added to {primary_mapping_table}')\n\n # check if errors were encountered and report any\n if new_mappings_job.errors:\n LOGGER.error(f'Query job finished with errors. See details of job '\n f'with job_id_prefix {job_prefix} and labels {labels}')\n else:\n LOGGER.info('Query job finished without errors.')\n\n\ndef check_table_name(name_str):\n \"\"\"\n Make sure the tablename provided follows the fully qualified format.\n\n If the table name cannot be split into three sections by splitting on a\n dot, '.', then reject the provided name as incomplete.\n\n :param name_str: The name of the table as provided by the end user.\n\n :return: a fully qualified table name string.\n :raises: ValueError if the name cannot be split.\n \"\"\"\n name_parts = name_str.split('.')\n if len(name_parts) != 3:\n raise ValueError(f'A fully qualified table name must be of the form '\n f'.. . You '\n f'provided {name_str}')\n\n return name_str\n\n\ndef check_email_address(address_str):\n \"\"\"\n Make sure the string provided looks like an email address.\n\n If the string does not contain `@`, then reject the provided string.\n\n :param address_str: The email address as provided by the end user.\n\n :return: a validated email address.\n :raises: ValueError if the address does not contain `@`.\n \"\"\"\n if '@' not in address_str:\n raise ValueError(f'An email address must be specified. '\n f'You supplied {address_str}')\n\n return address_str\n\n\ndef process_mappings(raw_args=None):\n \"\"\"\n Allow mapping arguments to be validated from other python modules.\n\n Use parser to validate arguments and then run mapping storage. This\n is not strictly required, but will help ensure the\n `store_to_primary_mapping_table` function works as designed.\n\n :params raw_args: If provided, a list of arguments and values.\n If not provided, defaults to command line values.\n \"\"\"\n LOGGER.info(\"Beginning pid/rid/shift storage process.\")\n\n parser = argparse.ArgumentParser(\n description='Add new mappings to our primary pid/rid mapping table.',\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\n '-r',\n '--fq_rdr_mapping',\n action='store',\n dest='rdr_mapping',\n help=('The fully qualified rdr mapping table name. '\n 'The project_id will be extracted from this table name.'),\n type=check_table_name,\n required=True)\n parser.add_argument(\n '-i',\n '--run_as',\n action='store',\n dest='run_as',\n help=('The email address of the service account to impersonate.'),\n type=check_email_address)\n args = parser.parse_args()\n\n store_to_primary_mapping_table(args.rdr_mapping, run_as=args.run_as)\n\n LOGGER.info(\"Finished pid/rid/shift storage process.\")\n\n\nif __name__ == '__main__':\n from utils import pipeline_logging\n\n pipeline_logging.configure()\n process_mappings()\n","sub_path":"data_steward/tools/store_mappings.py","file_name":"store_mappings.py","file_ext":"py","file_size_in_byte":8349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"294908721","text":"def cria_matriz(num_linhas, num_colunas):\n matriz = [] #lista vazia\n for i in range(num_linhas):\n linha = []\n for j in range(num_colunas):\n linha.append(0)\n matriz.append(linha)\n\n for i in range(num_colunas):\n for j in range(num_linhas):\n matriz[j][i] = int(input(\"Digite o elemento [\" + str(j) + \"][\" + str(i) + \"]: \"))\n\n return matriz\n\ncria_matriz(2,3)","sub_path":"Exercicios_Resolvidos/Parte 2/Treino/exercicio_matriz-3.py","file_name":"exercicio_matriz-3.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"434477061","text":"import numpy as np\nimport cv2\n\nMIN_MATCH_COUNT = 10\n\nimg1 = cv2.imread('C:/Users/User/PycharmProjects/untitled1/heart.png',1) # queryImage\nimg2 = cv2.imread('C:/Users/User/PycharmProjects/untitled1/gg.jpg',1) # trainImage\n\nimg1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\nimg2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\ncv2.imshow('loadimage', img2)\ncv2.waitKey(0)\n\n# Initiate SURF detector\nsurf = cv2.xfeatures2d.SURF_create()\n\n# find the keypoints and descriptors with SURF\nkp1, des1 = surf.detectAndCompute(img1_gray,None)\nkp2, des2 = surf.detectAndCompute(img2_gray,None)\n\n# FLANN parameters\nFLANN_INDEX_KDTREE = 0\nindex_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\nsearch_params = dict(checks=50) # or pass empty dictionary\n\nflann = cv2.FlannBasedMatcher(index_params,search_params)\n\nmatches = flann.knnMatch(des1,des2,k=2)\n\n# store all the good matches as per Lowe's ratio test.\ngood = []\nfor m,n in matches:\n if m.distance < 0.7 * n.distance:\n good.append(m)\n\nif len(good)>MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)\n\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)\n matchesMask = mask.ravel().tolist()\n\n h,w = img1_gray.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n dst = cv2.perspectiveTransform(pts,M)\n\n img2_gray = cv2.polylines(img2_gray,[np.int32(dst)],True,255,3, cv2.LINE_AA)\n\nelse:\n print(\"Not enough matches are found - %d/%d\" % (len(good),MIN_MATCH_COUNT))\n matchesMask = None\n\ndraw_params = dict(matchColor = (0,255,0), # draw matches in green color\n singlePointColor = None,\n matchesMask = matchesMask, # draw only inliers\n flags = 2)\n\nimg3 = cv2.drawMatches(img1_gray,kp1,img2_gray,kp2,good,None,**draw_params)\n\ncv2.imshow('SURF', img3)\ncv2.waitKey(0)\n\npoint = np.int32(dst)\npoint1 = point[0][0]\npoint2 = point[1][0]\npoint3 = point[2][0]\npoint4 = point[3][0]\n\nx = int((point1[0]+point2[0])/2)\ny = int((point1[1]+point4[1])/2)\nw = int((point3[0]+point4[0])/2)\nh = int((point2[1]+point3[1])/2)\n\nimg_trim = img2[y:h, x:w]\ncv2.imshow('trim', img_trim)\ncv2.waitKey(0)\n\nimg_trim_hsv = cv2.cvtColor(img_trim, cv2.COLOR_BGR2HSV)\n\nlower_blue = np.array([110, 30, 100])\nupper_blue = np.array([130, 255, 255])\nlower_green = np.array([50, 30, 100])\nupper_green = np.array([70, 255, 255])\nlower_red = np.array([-10, 30, 100])\nupper_red = np.array([255, 255, 255])\n\nmask_red = cv2.inRange(img_trim_hsv, lower_red, upper_red)\n\nres = cv2.bitwise_and(img_trim, img_trim, mask=mask_red )\n\ncv2.imshow('red', res)\ncv2.waitKey(0)\n\nres2 = img_trim-res\ncv2.imshow('res',res2)\ncv2.waitKey(0)\n\nres2_ycrcb = cv2.cvtColor(res2, cv2.COLOR_BGR2YCR_CB)\ny, cr, cb = cv2.split(res2_ycrcb)\n\ny_mean = np.mean(y)\ncr_mean = np.mean(cr)\ncb_mean = np.mean(cb)\n\nym = int(round(239 - y_mean))\ncrm = int(round(128 - cr_mean))\ncbm = int(round(128 - cb_mean))\n\ny2 = cv2.add(y, ym)\ncr2 = cv2.add(cr, crm)\ncb2 = cv2.add(cb, cbm)\n\nres2_ycrcb = cv2.merge((y2, cr2, cb2))\nres2 = cv2.cvtColor(res2_ycrcb, cv2.COLOR_YCR_CB2BGR)\n\ncv2.imshow('loadimage2', res2)\ncv2.waitKey(0)\n\nimg2_ycrcb = cv2.cvtColor(img2, cv2.COLOR_BGR2YCR_CB)\nimg2_y, img2_cr, img2_cb = cv2.split(img2_ycrcb)\n\nimg2_y2 = cv2.add(img2_y, ym)\nimg2_cr2 = cv2.add(img2_cr, crm)\nimg2_cb2 = cv2.add(img2_cb, cbm)\n\nimg2_ycrcb = cv2.merge((img2_y, img2_cr2, img2_cb2))\nimg2 = cv2.cvtColor(img2_ycrcb, cv2.COLOR_YCR_CB2BGR)\n\ncv2.imshow('loadimage3', img2)\ncv2.waitKey(0)\n\n","sub_path":"opencv/matching3.py","file_name":"matching3.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"16630706","text":"# Root Routing Configuration for Channels.\n# It is similar to a Django URLconf in that it tells Channels\n# what code to run\n# when an HTTP request is received by the Channels server.\n\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\n\nimport chat.routing\n\n# ProtocolTypeRouter checks if it is a WebSocket connection\n# AuthMiddlewareStack populates the connection’s scope\n# with a reference to the currently authenticated user.\n# URLRouter examines the HTTP path of the connection\n# to route it to a particular consumer\n\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n chat.routing.websocket_urlpatterns\n )\n ),\n})","sub_path":"lifebase/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"564484840","text":"'''\nAuthor: Chuck Stewart\nDate: February 24, 2016\n\nPurpose: A module to read in the Social Security Administration's top\n 250 baby names for each year from 1880 up to and including 2014.\n\nUsage: \n 1. Import the module\n\n 2. Call read_names.read_from_file(fn) where fn is the file\n containing the names. This returns a boolean, which for the\n purposes of the homework can be safely ignored.\n\n 3. (names, counts) = read_names.top_in_year(year, f_or_m) where\n year is an int and f_or_m is a single character to indicate\n whether female ('F' or 'f') names are requested or male ('M' or\n 'm') names are requested. This function returns a tuple of\n lists, where the first list is the names and the second list is\n the count of occurrences of that name.\n'''\n\nimport sys\n\n'''\nThe following are the global lists and int storing all of the\ninformation read in. All of this really should be in a Python class\nobject, but at this point in the semester we have not studied these.\n'''\nall_female_names = []\nall_female_counts = []\nall_male_names = []\nall_male_counts = []\nfirst_year = -1\n\n\ndef read_from_file( file_name ):\n '''\n Read from file_name. The format is the year, followed by the top\n 250 female names,followed by the top 250 male names. This repeats\n for each year in order. Here are the first four lines to show the\n form of each line \n 1880\n Mary,F,7065\n Anna,F,2604\n Emma,F,2003\n '''\n in_f = open(file_name,'r')\n\n ''' These are the counts for one year... '''\n female_names = []\n female_counts = []\n male_names = []\n male_counts = []\n year = -1 # this is reset when the very first year is read in\n line_num = 0\n \n ''' Tell Python to use these outside variables '''\n global all_female_names\n global all_female_counts\n global all_male_names\n global all_male_counts\n global first_year\n\n ''' Handle one line of input at a time '''\n for line in in_f:\n line = line.strip().split(',')\n line_num += 1\n\n # Handle the special case of the very first line and year\n if first_year == -1 and len(line) == 1 and line[0].isdigit():\n first_year = int(line[0])\n year = first_year\n\n # Error check on the format of the first line\n elif first_year == -1:\n print(\"Error: initial format on line number\", line_num)\n return False\n\n # After the first line we'll end up here each time. This\n # line is to test for the start of the next year and will\n # succeed only after 500 names have been read\n elif len(line) == 1 and line[0].isdigit(): \n # Add the names from the year just completely read to the\n # end of the global lists of lists\n all_female_names.append( female_names )\n all_female_counts.append( female_counts )\n all_male_names.append( male_names )\n all_male_counts.append( male_counts )\n\n # Reset the lists for the next year\n female_names = []\n female_counts = []\n male_names = []\n male_counts = []\n year = int(line[0])\n\n # Check for a well-formatted line for a female name\n elif len(line)==3 and line[1].lower() == 'f' and line[2].isdigit():\n female_names.append( line[0] )\n female_counts.append( int(line[2]) )\n\n # Check for a well-formatted line for a male name\n elif len(line)==3 and line[1].lower() == 'm' and line[2].isdigit():\n male_names.append( line[0] )\n male_counts.append( int(line[2]) )\n\n # If we get here there is a formatting error somewhere and we\n # don't know what else to do so we quit\n else:\n print(\"Error: internal format on line number\", line_num)\n return False\n\n # We get to here after the entire file has been read. We now\n # need to save the last year's lists to the global lists.\n all_female_names.append( female_names )\n all_female_counts.append( female_counts )\n all_male_names.append( male_names )\n all_male_counts.append( male_counts )\n\n # We are done!\n return True\n \n\ndef top_in_year( year, f_or_m ):\n ''' For the given year, access the list of names and the list of\n counts for the names. Return empty lists if the year is out\n of range.\n '''\n if year < first_year or year > 2014:\n return ([], [])\n\n index = year - first_year\n if f_or_m.lower() == 'f':\n return (all_female_names[index], all_female_counts[index])\n else:\n return (all_male_names[index], all_male_counts[index])\n\n\n'''\nThe following code is only run if the module is being executed as a program.\n'''\nif __name__ == \"__main__\":\n fn = \"top_names_1880_to_2014.txt\"\n\n if read_from_file( fn ):\n print(\"Successful read\")\n else:\n print(\"Read failed\")\n sys.exit()\n\n (names,counts) = top_in_year( 1883, 'F')\n for i in range(10):\n print(i, names[i], counts[i])\n\n print()\n (names,counts) = top_in_year( 1885, 'M')\n for i in range(10):\n print(i, names[i], counts[i])\n\n \n \n","sub_path":"CSCI_1100/Week_5/HW_3/read_names.py","file_name":"read_names.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616075483","text":"#coding:utf-8\n\nimport sys\nimport numpy as np\nfrom DataPreProcessing import (\n test_features,test_targets\n , train_features,train_targets\n , val_features, val_targets\n , scaled_features)\nfrom strategy import NeuralNetwork\n\nepochs = 100\nlearning_rate = 0.1\nhidden_nodes = 2\noutput_nodes = 1\n\nN_i = train_features.shape[1]\nnetwork = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)\n\n\ndef MSE(y, Y):\n return np.mean((y-Y)**2)\n\nlosses = {'train':[], 'validation':[]}\nfor e in range(epochs):\n batch = np.random.choice(train_features.index, size=128)\n for record,target in zip(train_features.ix[batch].values\n , train_targets.ix[batch]['cnt']):\n network.train(record, target)\n\n train_loss = MSE(network.run(train_features), train_targets)\n val_loss = MSE(network.run(val_features), val_targets)\n sys.stdout.write(\"\\rProgress: \" + str(100 * e/float(epochs))[:4] \\\n + \"% ... Training loss: \" + str(train_loss)[:5] \\\n + \" ... Validation loss: \" + str(val_loss)[:5])\n losses['train'].append(train_loss)\n losses['validation'].append(val_loss)\n\nfig, ax = plt.subplots(figsize=(8,4))\nmean, std = scaled_features['cnt']\npredictions = network.run(test_features)*std + mean\nax.plot(predictions[0], label='Prediction')\nax.plot((test_targets['cnt']*std + mean).values, label='Data')\nax.set_xlim(right=len(predictions))\nax.legend()\n\ndates = pd.to_datetime(rides.ix[test_data.index]['dteday'])\ndates = dates.apply(lambda d: d.strftime('%b %d'))\nax.set_xticks(np.arange(len(dates))[12::24])\n_ = ax.set_xticklabels(dates[12::24], rotation=45)","sub_path":"BikeSharing/BikeSharing.py","file_name":"BikeSharing.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"189772281","text":"\"\"\"This script shows how to calculate the number of reaches upstream of a target\"\"\"\n\nimport os\nimport sys\nsys.path.append('attribution_and_accumulation')\n\nfrom attribution_and_accumulation import Navigator\n\nREGION_ID = '07'\nTOPOLOGY_FILE = \"upstream_{}.npz\".format(REGION_ID)\nTOPOLOGY_FILE = os.path.join(\"WatershedTopology\", TOPOLOGY_FILE)\n\nREGION = Navigator(TOPOLOGY_FILE)\n\nTEST_REACH = 4867727\n\nN = len(REGION.all_upstream(TEST_REACH))\n\nprint(N)\n","sub_path":"Tools/navigator_demo.py","file_name":"navigator_demo.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"1332782","text":"from django import forms\nfrom django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.urls import reverse_lazy\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import CreateView, ListView, UpdateView, DeleteView, DetailView\nfrom django.db import transaction\nfrom django.db.models import Count, Avg\n\n\nfrom account.decorators import teacher_required\nfrom ..models import Quiz, Question, Answer\nfrom ..forms import QuestionForm, BaseAnswerInlineFormSet\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuizCreateView(CreateView):\n model = Quiz\n fields = ('name',)\n template_name = 'quiz/add_quiz.html'\n\n def form_valid(self, form):\n quiz = form.save(commit=False)\n quiz.owner = self.request.user\n quiz.save()\n messages.success(\n self.request, 'The quiz was created with success! Go ahead and add some questions now.')\n return redirect('quiz:question_add', quiz.pk)\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuizListView(ListView):\n model = Quiz\n ordering = ('name', )\n context_object_name = 'quizzes'\n template_name = 'quiz/quiz_list.html'\n\n def get_queryset(self):\n queryset = self.request.user.quizzes \\\n .annotate(questions_count=Count('questions', distinct=True))\n return queryset\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuizUpdateView(UpdateView):\n model = Quiz\n fields = ('name', )\n context_object_name = 'quiz'\n template_name = 'quiz/quiz_update.html'\n\n def get_context_data(self, **kwargs):\n kwargs['questions'] = self.get_object().questions.annotate(\n answers_count=Count('answers'))\n return super().get_context_data(**kwargs)\n\n def get_queryset(self):\n '''\n This method is an implicit object-level permission management\n This view will only match the ids of existing quizzes that belongs\n to the logged in user.\n '''\n return self.request.user.quizzes.all()\n\n def get_success_url(self):\n return reverse('quiz:quiz_update', kwargs={'pk': self.object.pk})\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuizDeleteView(DeleteView):\n model = Quiz\n context_object_name = 'quiz'\n template_name = 'quiz/quiz_delete_confirm.html'\n success_url = reverse_lazy('quiz:quiz_list')\n\n def delete(self, request, *args, **kwargs):\n quiz = self.get_object()\n messages.success(\n request, 'The quiz %s was deleted with success!' % quiz.name)\n return super().delete(request, *args, **kwargs)\n\n def get_queryset(self):\n return self.request.user.quizzes.all()\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuestionDeleteView(DeleteView):\n model = Question\n context_object_name = 'question'\n template_name = 'quiz/question_delete_confirm.html'\n pk_url_kwarg = 'question_pk'\n\n def get_context_data(self, **kwargs):\n question = self.get_object()\n kwargs['quiz'] = question.quiz\n return super().get_context_data(**kwargs)\n\n def delete(self, request, *args, **kwargs):\n question = self.get_object()\n messages.success(\n request, 'The question %s was deleted with success!' % question.text)\n return super().delete(request, *args, **kwargs)\n\n def get_queryset(self):\n return Question.objects.filter(quiz__owner=self.request.user)\n\n def get_success_url(self):\n question = self.get_object()\n return reverse('quiz:quiz_update', kwargs={'pk': question.quiz_id})\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass QuizResultsView(DetailView):\n model = Quiz\n context_object_name = 'quiz'\n template_name = 'quiz/teachers/quiz_results.html'\n\n def get_context_data(self, **kwargs):\n quiz = self.get_object()\n taken_quizzes = quiz.taken_quizzes.select_related(\n 'student__user').order_by('-date')\n total_taken_quizzes = taken_quizzes.count()\n quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score'))\n extra_context = {\n 'taken_quizzes': taken_quizzes,\n 'total_taken_quizzes': total_taken_quizzes,\n 'quiz_score': quiz_score\n }\n kwargs.update(extra_context)\n return super().get_context_data(**kwargs)\n\n def get_queryset(self):\n return self.request.user.quizzes.all()\n\n\n@login_required\n@teacher_required\ndef question_add(request, pk):\n\n quiz = get_object_or_404(Quiz, pk=pk, owner=request.user)\n\n if request.method == 'POST':\n form = QuestionForm(request.POST)\n if form.is_valid():\n question = form.save(commit=False)\n question.quiz = quiz\n question.save()\n messages.success(\n request, 'You may now add answers/options to the question.')\n return redirect('quiz:question_update', quiz.pk, question.pk)\n # quiz.pk, question.pk\n else:\n form = QuestionForm()\n\n return render(request, 'quiz/question_add.html', {'quiz': quiz, 'form': form})\n\n\n@login_required\n@teacher_required\ndef question_update(request, quiz_pk, question_pk):\n\n quiz = get_object_or_404(Quiz, pk=quiz_pk, owner=request.user)\n question = get_object_or_404(Question, pk=question_pk, quiz=quiz)\n\n AnswerFormSet = forms.inlineformset_factory(\n Question, # parent model\n Answer, # base model\n formset=BaseAnswerInlineFormSet,\n fields=('text', 'is_correct'),\n min_num=2,\n validate_min=True,\n max_num=10,\n validate_max=True\n )\n\n if request.method == 'POST':\n form = QuestionForm(request.POST, instance=question)\n formset = AnswerFormSet(request.POST, instance=question)\n if form.is_valid() and formset.is_valid():\n with transaction.atomic():\n form.save()\n formset.save()\n messages.success(\n request, 'Question and answers saved with success!')\n return redirect('quiz:quiz_update', quiz.pk)\n else:\n form = QuestionForm(instance=question)\n formset = AnswerFormSet(instance=question)\n\n return render(request, 'quiz/question_update.html', {\n 'quiz': quiz,\n 'question': question,\n 'form': form,\n 'formset': formset\n })\n","sub_path":"quiz/views/teachers.py","file_name":"teachers.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502049591","text":"import matplotlib\nmatplotlib.use(\"TKAgg\")\nfrom Tkinter import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\n\nclass plot_region(Frame):\n def __init__(self, master=None, **opt):\n Frame.__init__(self, master, opt)\n self.pack()\n self.plot_area()\n\n def plot_area(self):\n self.fig = Figure(figsize=(5, 5), dpi=150)\n self.canv = FigureCanvasTkAgg(self.fig, self)\n self.canv.show()\n self.canv.get_tk_widget().pack()\n\n def get_canvas(self):\n return (self.canv, self.fig)\n\n\nif __name__ == '__main__':\n plot_region().mainloop()","sub_path":"Ph2150/ps9_preq/plot_frame.py","file_name":"plot_frame.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"412771406","text":"#LJ\nimport json\nimport requests\n\nclass RunMain():\n '''\n RunMain类是为了get和post请求,\n 初始化实例之后通过run_main来判断请求类型\n '''\n\n #实例化后直接调用run_main()\n def __init__(self,url,method,data=None):\n self.res = self.run_main(url,method,data)\n\n\n #get请求\n def send_get(self,url,data):\n res = requests.get(url=url,data=data).json()\n return json.dumps(res,indent=2,sort_keys=True)\n\n\n #post请求\n def send_post(self,url,data):\n res = requests.get(url=url, data=data).json()\n return json.dumps(res, indent=2, sort_keys=True)\n\n def run_main(self,url,method,data=None):\n res = None\n if method == 'GET':\n res = self.send_get(url,data)\n else:\n res = self.send_post(url,data)\n return res\n\nif __name__ == '__main__':\n url= 'http://127.0.0.1:8000/web/login/'\n data = {\n 'username': 'lj',\n 'password': '123456'\n }\n run = RunMain(url,'GET',data)\n print(run.res)","sub_path":"interface/interfaceDemo.py","file_name":"interfaceDemo.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"291148187","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nimport json\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .models import Generator\n\n\ndef at_random(request, generator_number=None):\n try:\n if generator_number is not None:\n generator = Generator.objects.get(number=generator_number)\n next_card_number = Generator.objects.order_by('?').first().number\n else:\n generators = Generator.objects.order_by('?')\n generator = generators[0]\n next_card_number = generators[1].id\n\n context = {\n 'generator': generator,\n 'next_card_number': next_card_number\n }\n\n except ObjectDoesNotExist:\n context = {\n 'generator': None,\n 'next_card_number': None\n }\n\n return render(request, 'generators/at_random.html', context)\n","sub_path":"generators/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"207702800","text":"from Imdb_Etl.BucketManager import BucketManager\n\n\nclass TitlePrincipalsManager(BucketManager):\n def __init__(self, initiation_time):\n super().__init__(initiation_time)\n self.set_path_to_process(\"s3a://imdbtitleprincipalsz/processing/*/*/*/*/*.parquet\")\n self.set_bucket_name(BucketManager.get_bucket_name_from_config(\"title_principals\"))\n self.set_s3_resource()\n self.parse_bucket()\n self.change_files_to_processing_status()\n","sub_path":"Imdb_Etl/TitlePrincipalsManager.py","file_name":"TitlePrincipalsManager.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"9216891","text":"# $Id: SQLDDDB-Oracle.py,v 1.3 2008-09-30 13:17:36 marcocle Exp $\n__author__ = \"Marco Clemencic \"\n\nfrom Gaudi.Configuration import *\nfrom DetCond.Configuration import *\n\n##########################################################################\n# Technology dependent options to use the Conditions database\n##########################################################################\nfrom Configurables import COOLConfSvc\nCOOLConfSvc(UseLFCReplicaSvc = True)\n\nCondDBAccessSvc(\"DDDB\",\n ConnectionString = \"CondDB/DDDB\",\n CacheHighLevel = 1700\n )\n\nCondDBAccessSvc(\"LHCBCOND\",\n ConnectionString = \"CondDB/LHCBCOND\",\n CacheHighLevel = 200\n )\n\nCondDBAccessSvc(\"SIMCOND\",\n ConnectionString = \"CondDB/SIMCOND\",\n CacheHighLevel = 200\n )\n\nCondDBAccessSvc(\"DQFLAGS\",\n ConnectionString = \"CondDB/DQFLAGS\",\n\t\tCacheLowLevel = 5,\n CacheHighLevel = 10\n )\n\nCondDBAccessSvc(\"ONLINE\",\n ConnectionString = \"CondDBOnline/ONLINE\",\n )\n","sub_path":"DBASE/Det/SQLDDDB/options/SQLDDDB-Oracle.py","file_name":"SQLDDDB-Oracle.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"495909303","text":"import logging\nimport os\n\nfrom pyxus.resources.repository import DomainRepository, OrganizationRepository, InstanceRepository, SchemaRepository, ContextRepository\nfrom pyxus.utils.http_client import HttpClient\n\nLOGGER = logging.getLogger(__package__)\n\nENV_VAR_NEXUS_ENDPOINT = \"NEXUS_ENDPOINT\"\nENV_VAR_NEXUS_PREFIX = \"NEXUS_PREFIX\"\nENV_VAR_NEXUS_NAMESPACE = \"NEXUS_NAMESPACE\"\n\nclass NexusClient(object):\n SUPPORTED_VERSIONS = ['0.8.14']\n\n def __init__(self, scheme=None, host=None, prefix=None, alternative_namespace=None, token=None):\n self.version = None\n self.namespace = alternative_namespace if alternative_namespace is not None else \"{}://{}\".format(scheme, host)\n self.env = None\n self.config = NexusConfig(scheme, host, prefix, alternative_namespace)\n self._http_client = HttpClient(self.config.NEXUS_ENDPOINT, self.config.NEXUS_PREFIX, token=token)\n self.domains = DomainRepository(self._http_client)\n self.contexts = ContextRepository(self._http_client)\n self.organizations = OrganizationRepository(self._http_client)\n self.instances = InstanceRepository(self._http_client)\n self.schemas = SchemaRepository(self._http_client)\n\n def version_check(self, supported_versions=SUPPORTED_VERSIONS):\n server_metadata_url = '{}/'.format(self.config.NEXUS_ENDPOINT)\n\n response = self._http_client.get(server_metadata_url)\n\n if response is not None:\n service_name = response.get('name')\n self.version = response.get('version')\n self.env = response.get('env')\n if service_name == 'kg' and self.version in supported_versions:\n LOGGER.info('Version supported : %s\\nenv: %s',\n self.version, self.env)\n return True\n else:\n LOGGER.error('**Version unsupported**: %s\\nenv: %s',\n self.version, self.env)\n return True\n else:\n raise NexusException(response.reason)\n\n def get_fullpath_for_entity(self, entity):\n return \"{}{}\".format(self.config.NEXUS_NAMESPACE, entity.path)\n\n\nclass NexusConfig(object):\n\n def __init__(self, scheme=None, host=None, nexus_prefix=None, nexus_namespace=None):\n if host is None and scheme is None and ENV_VAR_NEXUS_ENDPOINT in os.environ:\n self.NEXUS_ENDPOINT = os.environ.get(ENV_VAR_NEXUS_ENDPOINT)\n elif host is not None and scheme is not None:\n self.NEXUS_ENDPOINT = \"{}://{}\".format(scheme, host)\n else:\n self.NEXUS_ENDPOINT = None\n self.NEXUS_PREFIX = os.environ.get(ENV_VAR_NEXUS_PREFIX) if nexus_prefix is None and ENV_VAR_NEXUS_PREFIX in os.environ else nexus_prefix\n if nexus_namespace is None and ENV_VAR_NEXUS_NAMESPACE in os.environ:\n self.NEXUS_NAMESPACE = os.environ.get(ENV_VAR_NEXUS_NAMESPACE)\n else:\n self.NEXUS_NAMESPACE = nexus_namespace\n self._validate()\n\n def _validate(self):\n if self.NEXUS_ENDPOINT is None:\n raise ValueError(\"The Nexus endpoint is not set!\")\n if self.NEXUS_PREFIX is None:\n raise ValueError(\"The Nexus prefix is not set!\")\n if self.NEXUS_NAMESPACE is None:\n raise ValueError(\"The Nexus namespace is not set!\")\n\n\nclass NexusException(Exception):\n \"\"\"Exception raised when a Nexus call fails\n\n Attributes:\n http_status_code -- code returned by the API\n message -- message for the exception\n \"\"\"\n def __init__(self, message):\n self.message = message\n","sub_path":"pyxus/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"360958633","text":"# -*- coding: utf-8 -*-\n# @Author: yulidong\n# @Date: 2018-07-18 18:49:15\n# @Last Modified by: yulidong\n# @Last Modified time: 2018-08-27 11:37:42\nimport numpy as np\nimport os\nimport time\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Process,Lock\nfrom multiprocessing import Pool\nthread_num=10\ndef crop(object):\n ground=np.array((object==1).nonzero())\n x1=np.min(ground[0,:])\n x2=np.max(ground[0,:])\n y1=np.min(ground[1,:])\n y2=np.max(ground[1,:])\n size=np.sum(object)\n return x1,y1,x2+1,y2+1,size\ndef pre_matching(start,end):\n left_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/left/'\n right_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/right/'\n match_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/match/'\n left_files=os.listdir(left_dir)\n left_files.sort()\n right_files=os.listdir(right_dir)\n right_files.sort()\n # s_index=int(np.floor(length/thread_num*index))-2\n # e_index=int(np.floor(length/thread_num*(index+1)))+2\n # if e_index>length:\n # e_index=length\n # if s_index<0:\n # s_index=0\n for i in range(int(start),int(end)):\n left=np.load(os.path.join(left_dir,left_files[i]))[...,8]\n right=np.load(os.path.join(right_dir,right_files[i]))[...,8]\n pre=[]\n pre2=[]\n l_box=[]\n r_box=[]\n match=[]\n start_time=time.time()\n for m in range(int(np.max(left)+1)):\n object=np.where(left==m,1,0)\n if np.sum(object)>0:\n l_box.append(crop(object))\n else:\n l_box.append((0,0,1,1,1))\n l_box=np.array(l_box)\n for m in range(int(np.max(right)+1)):\n object=np.where(right==m,1,0)\n if np.sum(object)>0:\n r_box.append(crop(object))\n else:\n r_box.append((0,0,1,1,1))\n r_box=np.array(r_box)\n for m in range(int(np.max(left)+1)):\n x1,y1,x2,y2,size=l_box[m]\n if size==1:\n match.append(-1)\n continue\n left_object_m=np.where(left==m,1,-1)[x1:x2,y1:y2]\n x_matching=(np.min([np.ones_like(r_box[:,2])*x2,r_box[:,2]],0)-np.max([np.ones_like(r_box[:,0])*x1,r_box[:,0]],0))/(x2-x1)\n x_matching=np.where(x_matching>0.8,1,0)\n y_matching=np.min([(r_box[:,3]-r_box[:,1]),np.ones_like(r_box[:,0])*(y2-y1)],0)/np.max([(r_box[:,3]-r_box[:,1]), \\\n np.ones_like(r_box[:,0])*(y2-y1)],0)\n y_matching=np.where(y_matching>0.5,1,0)\n y_check=np.where(r_box[:,1]<=y2,1,0)\n y_matching=y_matching*y_check\n matching=x_matching*y_matching\n overlap=[]\n for n in range(matching.shape[0]):\n if matching[n]==1:\n r_x1,r_y1,r_x2,r_y2,r_size=r_box[n]\n right_object_n=np.where(right==n,1,0)[x1:x2,r_y1:r_y2]\n if (r_y2-r_y1)>(y2-y1):\n shift=[]\n for k in range((r_y2-r_y1)-(y2-y1)+1):\n tmp_overelap=left_object_m-right_object_n[:,k:k+y2-y1]\n shift.append(np.sum(np.where(tmp_overelap==0,1,0))/np.max([size,r_size]))\n else:\n shift=[]\n for k in range((y2-y1)-(r_y2-r_y1)+1):\n tmp_overelap=right_object_n-left_object_m[:,k:k+r_y2-r_y1]\n shift.append(np.sum(np.where(tmp_overelap==0,1,0))/np.max([size,r_size]))\n overlap.append(np.max(shift))\n else:\n overlap.append(-1)\n if np.max(overlap)>0:\n match.append(np.argmax(overlap))\n else:\n match.append(-1)\n match=np.array(match)\n pre.append([l_box,r_box,match])\n #min_d=np.array(np.max([np.where(match==-1,0,r_box[match,1]+l_box[:,1]-l_box[:,3]),np.zeros_like(match)],0))\n #max_d=np.array(np.min([np.where(match==-1,l_box[:,3],r_box[match,3]+l_box[:,3]-l_box[:,1]),min_d+300],0))\n variance_d=np.floor((l_box[:,3]-l_box[:,1])/10).astype(np.int)\n min_d=np.where(match==-1,0,np.max([l_box[:,1]-r_box[match,1]-variance_d,np.zeros_like(match)],0))\n max_d=np.where(match==-1,192,np.min([l_box[:,3]-r_box[match,3]+variance_d,np.ones_like(match)*192],0))\n # if min_d>l_box[:,2]:\n # min_d=0\n # else:\n # min_d=np.max([min_d,0])\n\n min_d=np.where(min_d>l_box[:,3],0,np.max([min_d,np.zeros_like(match)],0))\n max_d=np.where(max_d<=min_d,min_d+192,max_d)\n max_d=np.min([max_d,l_box[:,3]],0)\n pre2.append(np.array([min_d,max_d]))\n pre_match=np.array([pre,pre2])\n np.save(os.path.join(match_dir,left_files[i]),pre_match)\n print('thread:%d,doing:%d,time:%.3f' % (end/440,i,time.time()-start_time))\n\n\nprocess = []\nleft_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/left/'\nleft_files=os.listdir(left_dir)\nleft_files.sort()\nlength=len(left_files)\nstart=[]\nend=[]\np = Pool(thread_num)\nfor z in range(thread_num):\n start.append(z*length/10)\n end.append((z+1)*length/10)\nfor z in range(thread_num):\n p.apply_async(pre_matching, args=(start[z],end[z]))\n\np.close()\np.join()\n#pre_matching(0,1)\nprint('end')\n","sub_path":"back of PSSM/PSSM/pre_matching-20180827142110.py","file_name":"pre_matching-20180827142110.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"512895182","text":"import cv2, os\r\nimport numpy as np\r\nfrom fd import *\r\n#from pprint import pprint\r\n\r\ndef normalize_intensity(image):\r\n \"\"\" This method normalizes the size and pixel intensity of an image.\"\"\"\r\n is_color = len(image.shape) == 3\r\n if is_color:\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n image = cv2.equalizeHist(image)\r\n return image\r\n\r\n\r\ndef read_face(face, size=(100, 100)):\r\n \"\"\" This method open and resize the image into size specified\"\"\"\r\n if isinstance(face, basestring):\r\n face = cv2.imread(face, 0)\r\n face_norm = normalize_intensity(face)\r\n else:\r\n face_norm = normalize_intensity(face)\r\n if face_norm.shape < size:\r\n face_resized = cv2.resize(face_norm, size, interpolation=cv2.INTER_AREA)\r\n else:\r\n face_resized = cv2.resize(face_norm, size, interpolation=cv2.INTER_CUBIC)\r\n return face_resized\r\n\r\ndef get_labels_faces(dataset_dir):\r\n \"\"\" This method generate the labels and faces\"\"\"\r\n labels_ppl = {}\r\n images = []\r\n labels = []\r\n i = 0\r\n for path, dir, file in os.walk(dataset_dir):\r\n for d in dir:\r\n for f in os.listdir(os.path.join(dataset_dir, d)):\r\n images.append(read_face(os.path.join(dataset_dir, d, f)))\r\n labels.append(i)\r\n labels_ppl[i] = d\r\n i+=1\r\n return labels, images, labels_ppl\r\n\r\n\r\ndef main():\r\n labels, images, labels_ppl = get_labels_faces(\"data/face_dataset\")\r\n recognizer = cv2.face.EigenFaceRecognizer_create()\r\n threshold = 10000\r\n recognizer.train(images, np.array(labels))\r\n eigenvectors = recognizer.getEigenVectors()\r\n eigenfaces = np.transpose(eigenvectors*255)\r\n for i,eigenface in enumerate(eigenfaces):\r\n eigenface = (eigenface-np.min(eigenface))/(np.max(eigenface)-np.min(eigenface))\r\n cv2.imwrite('ef%d.jpg'%i,(eigenface*255).astype(np.uint8).reshape(100,100))\r\n\r\n raw_input(\"Press ENTER to start recognition\")\r\n\r\n fd = CascadeClassifier(\"classifier/haarcascade_frontalface_default.xml\", \"classifier/haarcascade_eye.xml\")\r\n video_capture = cv2.VideoCapture(0)\r\n while True:\r\n # Capture frame-by-frame\r\n ret, frame = video_capture.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces_coord, faces_img = fd.detectMultiScale(gray)\r\n faces = [read_face(face) for face in faces_img]\r\n if len(faces_coord):\r\n for i, face in enumerate(faces):\r\n pred, conf = recognizer.predict(face)\r\n print (\"Prediction: \" + str(pred))\r\n print ('Confidence: ' + str(round(conf)))\r\n print ('Threshold: ' + str(threshold))\r\n\r\n if conf < threshold:\r\n cv2.putText(frame, labels_ppl[pred].capitalize(),\r\n (faces_coord[i][0], faces_coord[i][1] - 2),\r\n cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,\r\n cv2.LINE_AA)\r\n if len(faces_coord[i]) == 4:\r\n x,y,w,h = faces_coord[i]\r\n cv2.rectangle(frame, (x,y), (x+w,y+h), (206, 0, 209), thickness=2)\r\n elif len(faces_coord[i]) == 8:\r\n pts = map(tuple, np.array(faces_coord[i]).reshape(4,2).tolist())\r\n cv2.polylines(frame, np.int32([pts]), True, (206, 0, 209), 2)\r\n else:\r\n cv2.putText(frame, \"Unknown\",\r\n (faces_coord[i][0], faces_coord[i][1]),\r\n cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,\r\n cv2.LINE_AA)\r\n\r\n\r\n # Display the resulting frame\r\n cv2.imshow('Video', frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Face Recogition/Face_recogition.py","file_name":"Face_recogition.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"376282390","text":"from torchvision import transforms\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom data_loader23 import transformer_loader\nimport math\nimport time\nimport copy\nimport random\nimport os\nclass Trans(nn.Module):\n def __init__(self):\n super(Trans, self).__init__()\n self.encoder_layer = nn.TransformerEncoderLayer(d_model=100, nhead=2,dropout=0.3,dim_feedforward=1024)\n self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=6,norm=\"T\")\n self.linear = nn.Sequential(nn.Flatten(),\n nn.Linear(100*20, 512),\n nn.Dropout(0.1),\n # nn.Linear(1024, 512),\n # nn.Dropout(0.1),\n nn.Linear(512, 3),\n nn.Dropout(0.1),\n nn.Softmax())\n\n def forward(self,x):\n # print(x.size())\n x=self.transformer_encoder(x)\n # print(x.size())\n x=self.linear(x)\n return x\n\ndef binary_acc(preds, y):\n\n # preds = torch.round(preds)\n score_p, prediction = torch.max(preds, 1)\n score_t, target = torch.max(y, 1)\n # print(\"hhhhhhhhhhhhhhh\")\n # print(prediction)\n # print(target)\n\n correct = torch.eq(prediction, target).float()\n acc = correct.sum() /( len(correct))\n return acc\n\n\n#训练函数\ndef train(model, iterator, optimizer, criteon):\n\n avg_loss = []\n avg_acc = []\n model.train() #表示进入训练模式\n # print(\"-------------------\")3\n # print(len(iterator))\n for i, (data,label,mask) in enumerate(iterator):\n # print(\"*****************\")\n # print(data.size)\n # print(label.size())\n # print(mask.size)\n data=Variable(data).float().cuda()\n mask=Variable(mask).float().cuda()\n label=Variable(label).float().cuda()\n\n # data = Variable(data).type(torch.LongTensor)\n pred = model(data)\n\n # print(pred.size())\n # print(\"hhhhhhhhhhhh\")\n # similarity = torch.cosine_similarity(pred, label)\n #\n # loss = 1 - similarity\n loss = criteon(pred, label)\n acc = binary_acc(pred, label).item() #计算每个batch的准确率\n avg_loss.append(loss.item())\n avg_acc.append(acc)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n avg_acc = np.array(avg_acc).mean()\n avg_loss = np.array(avg_loss).mean()\n return avg_loss, avg_acc\n\n\n#评估函数\ndef evaluate(model, iterator, criteon):\n\n avg_loss = []\n avg_acc = []\n model.eval() #表示进入测试模式\n\n with torch.no_grad():\n for (data,label,mask) in iterator:\n data = Variable(data).float().cuda()\n mask = Variable(mask).float().cuda()\n label = Variable(label).float().cuda()\n pred = model(data)\n # score_p, prediction = torch.max(pred, 1)\n # score_t, target = torch.max(label, 1)\n # print(\"hhhhhhhhhhhhhhh\")\n # print(prediction)\n # print(target)\n loss = criteon(pred,label)\n acc = binary_acc(pred, label).item()\n avg_loss.append(loss.item())\n avg_acc.append(acc)\n\n avg_loss = np.array(avg_loss).mean()\n avg_acc = np.array(avg_acc).mean()\n return avg_loss, avg_acc\nif __name__==\"__main__\":\n\n from scipy.io import loadmat\n import numpy as np\n import random\n import os\n\n data = loadmat(\"MCAD_AFQ_competition.mat\", mat_dtype=True)\n # print(data.keys())\n # print(data[\"train_set\"])\n # print(data[\"train_set\"]0][0][.shape)\n train_set = data[\"train_set\"]\n train_diagnose = data[\"train_diagnose\"]\n all_data_list=[]\n # for i,item in enumerate(train_diagnose):\n # if(item[0]>1):\n # all_data_list.append(str(i)+\".npy\")\n\n\n all_data_list = os.listdir(\"./new_data/\")\n len_train_list=len(all_data_list)\n random.shuffle(all_data_list)\n val1,val2,val3,val4,val5=all_data_list[:int(len_train_list*0.2)],all_data_list[int(len_train_list*0.2):int(len_train_list*0.4)],all_data_list[int(len_train_list*0.4):int(len_train_list*0.6)],all_data_list[int(len_train_list*0.6):int(len_train_list*0.8)],all_data_list[int(len_train_list*0.8):]\n list_vals=[val1,val2,val3,val4,val5]\n for item in list_vals:\n val_list=item\n print(val_list)\n # val_list = random.sample(all_data_list, int(700 * 0.2))\n train_list = [item for item in all_data_list if item not in val_list]\n # random.shuffle(train_list)\n train_dataset = transformer_loader(train_list,\n transform=transforms.Compose([\n transforms.ToTensor(),\n\n ]))\n train_iterator = DataLoader(train_dataset, batch_size=32,\n shuffle=True, num_workers=1)\n print(len(train_list))\n print(len(train_iterator))\n dev_dataset = transformer_loader(val_list,\n transform=transforms.Compose([\n transforms.ToTensor(),\n ]))\n\n dev_iterator = DataLoader(dev_dataset, batch_size=32,\n shuffle=False, num_workers=1)\n\n # model=resnet18()\n # model =MyTransformerModel(p_drop=0.12).cuda()\n model=Trans().cuda()\n\n optimizer = optim.Adam(model.parameters(), lr=1e-5)\n criteon = nn.BCELoss()\n accs=[]\n losses_list=[]\n best_valid_acc = float('-inf')\n for epoch in range(100):\n start_time = time.time()\n train_loss, train_acc = train(model, train_iterator, optimizer, criteon)\n dev_loss, dev_acc = evaluate(model, dev_iterator, criteon)\n end_time = time.time()\n epoch_mins, epoch_secs = divmod(end_time - start_time, 60)\n if dev_acc > best_valid_acc: #只要模型效果变好,就保存\n best_valid_acc = dev_acc\n torch.save(model.state_dict(),'wordavg-model23.pt')\n print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs:.2f}s')\n print(f'\\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')\n print(f'\\t Val. Loss: {dev_loss:.3f} | Val. Acc: {dev_acc*100:.2f}%')\n accs.append(dev_acc)\n losses_list.append(dev_loss)\n import matplotlib.pyplot as plt\n plt.plot(range(100),losses_list)\n plt.show()\n plt.plot(range(100),accs)\n plt.show()\n","sub_path":"transformer123.py","file_name":"transformer123.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"465429261","text":"# if we try to get input in function parameter right away, it is a bit harder to really use exceptions to test input\ndef convert_str_to_float():\n\t'''\n\twhen function called:\n\t\ttry: asks user for input.\n\t\t\twill return input if input can be converted to a float\n\t\texcept ValueError:\n\t\t\ttells user to try again. ValueError found; input invalid.\n\t'''\n\twhile 1 > 0:\n\t\ttry:\n\t\t\tuinput=float(input('enter a float >>>'))\n\t\t\treturn uinput\n\t\texcept ValueError:\n\t\t\tprint('please try again')\nprint(convert_str_to_float())\n# have to print([function called]) in order to print result\n","sub_path":"IntroToProgramming/ch4questions_functions/convstringtofloat.py","file_name":"convstringtofloat.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"295191947","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 12 17:29:56 2017\n\n@author: xueyanmei\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import Lasso\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import GridSearchCV, train_test_split, cross_val_score\nfrom sklearn.linear_model import Ridge, RidgeCV\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\n\n\n# read the test date\ndata = pd.read_excel(\"/Users/xueyanmei/Downloads/test data1.xlsx\")\n\nminutes = data[\"minutes\"]\nn = np.logical_and(minutes > 10, minutes < 120)\nnew_data = data[n]\n\n#Get useful features\ndf = new_data[['day of the week', 'Age', 'sex', 'minutes', 'anatomy', 'patient type',\n 'pregnant', 'time', 'resource id', 'insured relation', 'hispanic', 'Ethnic code']]\n\n#Split target variable and features\ny_data = df['minutes'].values\nx_data = df.drop('minutes', axis = 1).values\n\n#split the train and test set\n(x_train, x_test, y_train, y_test) = train_test_split(x_data, y_data, test_size = 0.25)\n\n#build the lasso model\nlasso = Lasso(alpha =0.001, normalize=True)\nlasso.fit(x_train, y_train)\ncvscore_lasso = cross_val_score(lasso, x_data, y_data, cv=10)\ny_pred_lasso=lasso.predict(x_test)\nprint(\"R^2: {}\".format(lasso.score(x_test, y_test)))\nrmse_lasso = np.sqrt(mean_squared_error(y_test, y_pred_lasso))\nprint(\"Root Mean Squared Error: {}\".format(rmse_lasso))\n\n# build linear regression with regularization\nreg = RidgeCV(alphas = [0.1, 1.0, 10.0])\nreg.fit(x_train, y_train)\nreg.alpha_ \nest = Pipeline([('poly', PolynomialFeatures(2)), \n ('linear', Ridge(alpha=1))])\nest.fit(x_train, y_train)\nest_pred = est.predict(x_test)\nprint(\"R^2: {}\".format(lasso.score(x_test, est_pred)))\nrmse_ridge = np.sqrt(mean_squared_error(y_test, est_pred))\nprint(\"Root Mean Squared Error: {}\".format(rmse_ridge))\n\n#buid decision tree model\ndtr= DecisionTreeRegressor(max_depth=10)\ndtr.fit(x_train, y_train)\ny_pred_dtr = dtr.predict(x_test)\nrmse_dtr = np.sqrt(mean_squared_error(y_test, y_pred_dtr))\nprint(\"Root Mean Squared Error: {}\".format(rmse_dtr))\n\n","sub_path":"pyqt/studytime/trainingscript/studytimeRegression.py","file_name":"studytimeRegression.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"18530752","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom apps.loginregister.models import *\nfrom datetime import datetime\nimport bcrypt\nfrom apps.Courses.models import *\n\ndef index(request):\n if 'loggedid' in request.session:\n return redirect('/courses/')\n if 'errors' not in request.session:\n request.session['errors']={}\n context={'colleges':College.objects.all(),'departments':Dept.objects.all(),'errors':request.session['errors']}\n return render(request,'login.html',context)\n\ndef regval(request):\n validator= ValidationManager()\n if request.method=='POST':\n request.session['errors']={}\n errors= validator.validatereg(request.POST)\n if not len(errors):\n pwd=bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt())\n pwdcrpt=pwd.decode('utf-8')\n print(pwdcrpt)\n x=User.objects.create(first_name=request.POST['first_name'],last_name=request.POST['last_name'],email=request.POST['email'], username=request.POST['username'], passwordhash=pwdcrpt)\n x.college.add(College.objects.get(name=str(request.POST['college'])))\n x.save()\n request.session['loggedid']=User.objects.last().id\n return redirect('/courses/')\n else:\n request.session['errors']=errors\n return redirect('/login/')\n return redirect('/login/')\n\ndef loginval(request):\n validator= ValidationManager()\n request.session['errors']={}\n if request.method=='POST':\n errors= validator.validatelogin(request.POST)\n if not len(errors):\n request.session['loggedid']=User.objects.get(username=request.POST['username']).id\n return redirect ('/courses/')\n else:\n request.session['errors']=errors\n return redirect('/login/')\n\ndef logout(request):\n request.session.clear()\n return redirect('/login/')\n\ndef edituser(request):\n if 'errors' not in request.session:\n request.session['errors']={}\n x=User.objects.get(id=request.session['loggedid'])\n context={'errors':request.session['errors'], 'user':x, 'admin':x.accesslevel, 'courses':Course.objects.all(), 'departments':Dept.objects.all(), 'colleges':College.objects.all()}\n return render (request,'useredit.html',context)\n\ndef updateuser(request):\n validator= ValidationManager()\n if request.method=='POST':\n request.session['errors']={}\n errors= validator.validateupdate(request.POST)\n request.session['errors']=errors\n if len(errors)>0:\n return redirect('/login/profile/')\n x=User.objects.get(id=request.session['loggedid'])\n x.first_name=request.POST['first_name']\n x.last_name=request.POST['last_name']\n x.email=request.POST['email']\n x.username=request.POST['username']\n x.save()\n return redirect('/courses/')\n return redirect('/login/')","sub_path":"apps/loginregister/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"334798159","text":"# -*- coding: utf-8 -*-\n\nfrom django.core.mail import EmailMessage\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.db.models import Case, When, Value, BooleanField, Count\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfrom .forms import PostReplyForm, PrivateQuestionForm, QuestionForm, QuestionDeleteForm, PostReplyDeleteForm\nfrom .models import Question, Notice, FAQ, NewsLetter, Thesis, PostReply, SUBJECT_MENOPAUSE, SUBJECT_STUDY_OPERATION\nfrom examinees.models import Examinee\n#from tracking.models import Visitor\n\nimport datetime\nimport smtplib\n\nEMAIL_ID = settings.EMAIL_HOST_USER\nEMAIL_PASSWD = settings.EMAIL_HOST_PASSWORD\nEMAIL_HOST = settings.EMAIL_HOST\nEMAIL_PORT = settings.EMAIL_PORT\n\nMASTER_PW = settings.MASTER_PW\n\ndef index(request):\n\tend_time = datetime.datetime.now()\n\tstart_time = datetime.datetime(2019, 6, 1)\n\n\t#total_visit_count = Visitor.objects.stats(start_time, end_time)['total']\n\ttotal_visit_count = 0\n\ttotal_examinee_count = Examinee.objects.filter(is_tester=0).count()\n\n\tcontext = {\n\t\t'total_visit_count': '{}명'.format(format(total_visit_count, ',')),\n\t\t'total_examinee_count': '{}명'.format(format(total_examinee_count, ','))\n\t}\n\n\treturn render(request, 'index.html', context)\n\n\ndef intro_study_purpose(request):\n\treturn render(request, 'intro/study_purpose.html')\n\n\ndef intro_study_goal(request):\n\treturn render(request, 'intro/study_goal.html')\n\n\ndef study_method_examinees_status(request):\n\treturn render(request, 'study_method/examinees_status.html')\n\n\ndef study_method_collect_data(request):\n\treturn render(request, 'study_method/collect_data.html')\n\n\ndef study_result_thesis(request):\n\ttoday = datetime.datetime.today()\n\tthree_days_ago = today - datetime.timedelta(days=3)\n\tthesis_list = Thesis.objects.filter(is_open=True).order_by('-created_at').annotate(\n\t\treplies_count=Count('thesis_replies'),\n\t\tis_brand_new=Case(When(created_at__gte=three_days_ago, then=Value(True)),\n\t\t\t\t\t\t default=Value(False),\n\t\t\t\t\t\t output_field=BooleanField()))\n\tpaginator = Paginator(thesis_list, 10)\n\tpage = request.GET.get('page', 1)\n\tthesiss = paginator.page(page)\n\n\tcontext = {\n\t\t'thesiss': thesiss,\n\t}\n\n\treturn render(request, 'study_result/main_thesis.html', context)\n\n\ndef study_result_news_letter(request):\n\ttoday = datetime.datetime.today()\n\tthree_days_ago = today - datetime.timedelta(days=3)\n\tnews_letter_list = NewsLetter.objects.filter(is_open=True).order_by('-created_at').annotate(\n\t\treplies_count=Count('news_letter_replies'),\n\t\tis_brand_new=Case(When(created_at__gte=three_days_ago, then=Value(True)),\n\t\t\t\t\t\t default=Value(False),\n\t\t\t\t\t\t output_field=BooleanField()))\n\tpaginator = Paginator(news_letter_list, 10)\n\tpage = request.GET.get('page', 1)\n\tnews_letters = paginator.page(page)\n\n\tcontext = {\n\t\t'news_letters': news_letters,\n\t}\n\n\treturn render(request, 'study_result/news_letter.html', context)\n\n\ndef post_detail(request):\n\tdef do_error():\n\t\treturn HttpResponseRedirect(\"//kscs-kbsmc.net/app/\")\n\n\tcontent_type = request.GET.get('type', '')\n\tcontent_id = request.GET.get('id', '')\n\n\tif not content_type or not content_id:\n\t\treturn do_error()\n\n\tneed_show_reply = True\n\n\ttry:\n\t\tif content_type == \"notice\":\n\t\t\ttitle = \"공지사항\"\n\t\t\tpost = Notice.objects.get(id=content_id)\n\t\t\treplies = PostReply.objects.filter(notice=post)\n\n\t\telif content_type == \"faq\":\n\t\t\ttitle = \"FAQ\"\n\t\t\tpost = FAQ.objects.get(id=content_id)\n\t\t\treplies = PostReply.objects.none()\n\t\t\tneed_show_reply = False\n\n\t\telif content_type == \"question\":\n\t\t\ttitle = \"1:1문의\"\n\t\t\tpost = Question.objects.get(id=content_id)\n\t\t\treplies = PostReply.objects.filter(question=post)\n\n\t\telif content_type == \"thesis\":\n\t\t\ttitle = \"주요 논문\"\n\t\t\tpost = Thesis.objects.get(id=content_id)\n\t\t\treplies = PostReply.objects.filter(thesis=post)\n\n\t\telif content_type == \"news_letter\":\n\t\t\ttitle = \"뉴스레터\"\n\t\t\tpost = NewsLetter.objects.get(id=content_id)\n\t\t\treplies = PostReply.objects.filter(news_letter=post)\n\n\t\telse:\n\t\t\traise Exception()\n\texcept:\n\t\treturn do_error()\n\n\tcontext = {\n\t\t'comment_form': PostReplyForm(),\n\t\t'comment_delete_form': PostReplyDeleteForm(),\n\t\t'content_type': content_type,\n\t\t'title': title,\n\t\t'post': post,\n\t\t'replies': replies,\n\t\t'need_show_reply': need_show_reply\n\t}\n\n\tif content_type == \"question\":\n\t\tcontext['post_delete_form'] = QuestionDeleteForm()\n\n\tif request.method == 'POST':\n\t\tif 'content' in request.POST:\n\t\t\tform = PostReplyForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tpost_reply = form.save(commit=False)\n\n\t\t\t\thref = \"\"\n\t\t\t\tif content_type == \"notice\":\n\t\t\t\t\tpost_reply.notice = post\n\t\t\t\t\thref = \"https://kscs-kbsmc.net/user_app/notice/{}/change/\".format(\n\t\t\t\t\t\tpost.id,\n\t\t\t\t\t\tpost.id\n\t\t\t\t\t)\n\n\t\t\t\telif content_type == \"question\":\n\t\t\t\t\tpost_reply.question = post\n\t\t\t\t\thref = \"https://kscs-kbsmc.net/user_app/question/{}/change/\".format(\n\t\t\t\t\t\tpost.id,\n\t\t\t\t\t\tpost.id\n\t\t\t\t\t)\n\n\t\t\t\telif content_type == \"thesis\":\n\t\t\t\t\tpost_reply.thesis = post\n\t\t\t\t\thref = \"https://kscs-kbsmc.net/user_app/thesis/{}/change/\".format(\n\t\t\t\t\t\tpost.id,\n\t\t\t\t\t\tpost.id\n\t\t\t\t\t)\n\n\t\t\t\telif content_type == \"news_letter\":\n\t\t\t\t\tpost_reply.news_letter = post\n\t\t\t\t\thref = \"https://kscs-kbsmc.net/user_app/newsletter/{}/change/\".format(\n\t\t\t\t\t\tpost.id,\n\t\t\t\t\t\tpost.id\n\t\t\t\t\t)\n\n\t\t\t\tpost_reply.save()\n\n\t\t\t\tsend_email(\"[홈페이지] 새댓글 알림\", \"여성건강연구 홈페이지에 새로운 댓글이 올라왔습니다.

작성자: {}
내용: {}
작성시간: {}

{}\".format(\n\t\t\t\t\tpost_reply.name,\n\t\t\t\t\tpost_reply.content,\n\t\t\t\t\tpost_reply.created_at,\n\t\t\t\t\thref\n\t\t\t\t))\n\n\t\t\t\tmessages.error(request, \"댓글이 저장되었습니다.\")\n\n\t\telif 'post_reply_id' in request.POST:\n\t\t\tform = PostReplyDeleteForm(request.POST)\n\n\t\t\tif form.is_valid():\n\t\t\t\tpost_reply_id = request.POST.get('post_reply_id')\n\t\t\t\tpassword = request.POST.get('password')\n\n\t\t\t\ttry:\n\t\t\t\t\tpost_reply = PostReply.objects.get(id=post_reply_id, password=password)\n\t\t\t\t\tpost_reply.delete()\n\t\t\t\t\tmessages.error(request, \"댓글이 삭제되었습니다.\")\n\t\t\t\texcept:\n\t\t\t\t\tmessages.error(request, \"비밀번호가 올바르지 않습니다.\")\n\n\t\telif 'question_id' in request.POST:\n\t\t\tform = QuestionDeleteForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tquestion_id = request.POST.get('question_id')\n\t\t\t\tpassword = request.POST.get('password')\n\n\t\t\t\ttry:\n\t\t\t\t\tquestion = Question.objects.get(id=question_id, password=password)\n\t\t\t\t\tquestion.delete()\n\t\t\t\t\tmessages.error(request, \"게시글이 삭제되었습니다.\")\n\t\t\t\texcept:\n\t\t\t\t\tmessages.error(request, \"비밀번호가 올바르지 않습니다.\")\n\n\t\t\t\treturn HttpResponseRedirect(\"//kscs-kbsmc.net/app/question/inquiry/\")\n\n\t\treturn HttpResponseRedirect('https://kscs-kbsmc.net/app/question/detail/?id={}&type={}'.format(\n\t\t\tcontent_id, content_type\n\t\t))\n\n\treturn render(request, 'post_detail.html', context)\n\n\ndef question_write(request):\n\tcontext = {\n\t\t'form': QuestionForm()\n\t}\n\n\tif request.method == 'POST':\n\t\tform = QuestionForm(request.POST)\n\n\t\t# try:\n\t\tif form.is_valid():\n\t\t\tquestion = form.save(commit=False)\n\t\t\tquestion.save()\n\t\t\tmessages.error(request, \"문의글이 저장되었습니다.\")\n\n\t\t\tsend_email(\"[홈페이지] 새글 알림\", \"여성건강연구 홈페이지에 새로운 글이 올라왔습니다.

작성자: {}
문의종류: {}
작성시간: {}

{}\".format(\n\t\t\t\tquestion.name,\n\t\t\t\tquestion.get_subject_display(),\n\t\t\t\tquestion.created_at,\n\t\t\t\t\"
https://kscs-kbsmc.net/user_app/question/{}/change/\".format(question.id, question.id)\n\t\t\t))\n\t\t\treturn HttpResponseRedirect(\"//kscs-kbsmc.net/app/question/inquiry\")\n\t\telse:\n\t\t\tmessages.error(request, \"유효하지 않은 요청입니다.\")\n\t\t# except:\n\t\t# \tmessages.error(request, \"서버 오류가 발생하였습니다.\")\n\t\t# \treturn HttpResponseRedirect(\"//kscs-kbsmc.net/app/question/inquiry/\")\n\n\treturn render(request, 'question_write.html', context)\n\n\ndef question_notice(request):\n\ttoday = datetime.datetime.today()\n\tthree_days_ago = today - datetime.timedelta(days=3)\n\tnotice_list = Notice.objects.filter(is_open=True).order_by('-created_at').annotate(\n\t\treplies_count=Count('notice_replies'),\n\t\tis_brand_new=Case(When(created_at__gte=three_days_ago, then=Value(True)),\n\t\t\t\t\t\t default=Value(False),\n\t\t\t\t\t\t output_field=BooleanField()))\n\tpaginator = Paginator(notice_list, 10)\n\tpage = request.GET.get('page', 1)\n\tnotices = paginator.page(page)\n\n\tcontext = {\n\t\t'notices': notices,\n\t}\n\n\treturn render(request, 'question/notice.html', context)\n\n\ndef question_faq(request):\n\ttoday = datetime.datetime.today()\n\tthree_days_ago = today - datetime.timedelta(days=3)\n\n\tmenopause_faq_list = FAQ.objects.filter(is_open=True, subject=SUBJECT_MENOPAUSE).order_by('-created_at').annotate(\n\t\tis_brand_new=Case(When(created_at__gte=three_days_ago, then=Value(True)),\n\t\t\t\t\t\t default=Value(False), output_field=BooleanField()))\n\n\tstudy_faq_list = FAQ.objects.filter(is_open=True, subject=SUBJECT_STUDY_OPERATION).order_by('-created_at').annotate(\n\t\t\tis_brand_new=Case(When(created_at__gte=three_days_ago, then=Value(True)),\n\t\t\t\t\t\t\t default=Value(False), output_field=BooleanField()))\n\n\tpage = request.GET.get('page', 1)\n\tsubject = request.GET.get('subject', 'menopause')\n\n\tmenopause_paginator = Paginator(menopause_faq_list, 10)\n\tstudy_paginator = Paginator(study_faq_list, 10)\n\n\tif subject == 'study':\n\t\tmenopause_page = 1\n\t\tstudy_page = page\n\n\telse:\n\t\tmenopause_page = page\n\t\tstudy_page = 1\n\n\tmenopause_faqs = menopause_paginator.page(menopause_page)\n\tstudy_faqs = study_paginator.page(study_page)\n\n\tcontext = {\n\t\t'menopause_faqs': menopause_faqs,\n\t\t'study_faqs': study_faqs\n\t}\n\treturn render(request, 'question/faq.html', context)\n\n\ndef question_inquiry(request):\n\ttoday = datetime.datetime.today()\n\tyesterday = today - datetime.timedelta(days=1)\n\tquestion_list = Question.objects.all().order_by('-created_at').annotate(\n\t\treplies_count=Count('question_replies'),\n\t\tis_brand_new=Case(When(created_at__gte=yesterday, then=Value(True)),\n\t\t\t\t\t\t default=Value(False),\n\t\t\t\t\t\t output_field=BooleanField()))\n\tpaginator = Paginator(question_list, 10)\n\tpage = request.GET.get('page', 1)\n\tquestions = paginator.page(page)\n\n\tcontext = {\n\t\t'form': PrivateQuestionForm(),\n\t\t'questions': questions,\n\t}\n\n\tif request.method == 'POST':\n\t\tform = PrivateQuestionForm(request.POST)\n\n\t\ttry:\n\t\t\tif form.is_valid():\n\t\t\t\tquestion_id = int(form.cleaned_data.get('question_id'))\n\t\t\t\tpassword = form.cleaned_data.get('password')\n\n\t\t\t\tif password == MASTER_PW:\n\t\t\t\t\tquestion = Question.objects.get(\n\t\t\t\t\t\tid=question_id,\n\t\t\t\t\t)\n\n\t\t\t\telse:\n\t\t\t\t\tquestion = Question.objects.get(\n\t\t\t\t\t\tid=question_id,\n\t\t\t\t\t\tpassword=password\n\t\t\t\t\t)\n\n\t\t\t\treturn HttpResponseRedirect(\n\t\t\t\t\t\"//kscs-kbsmc.net/app/question/detail/?id={}&type=question\".format(question.id))\n\n\t\t\telse:\n\t\t\t\traise Exception()\n\t\texcept:\n\t\t\tmessages.error(request, \"비밀번호가 올바르지 않습니다.\")\n\t\t\treturn HttpResponseRedirect(\"//kscs-kbsmc.net/app/question/inquiry/\")\n\n\treturn render(request, 'question/inquiry.html', context)\n\n\ndef question_contact(request):\n\treturn render(request, 'question/contact.html')\n\n\ndef send_email(title, content):\n\tmessage = MIMEMultipart()\n\tmessage['From'] = EMAIL_ID\n\tmessage['To'] = \"kscs.kbsmc@samsung.com\"\n\t# message['To'] = \"elysiu_m@naver.com\"\n\tmessage['Subject'] = title\n\tmessage.attach(MIMEText(content, \"html\", \"utf-8\"))\n\n\temail_object = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)\n\temail_object.ehlo()\n\temail_object.starttls()\n\temail_object.ehlo()\n\temail_object.login(EMAIL_ID, EMAIL_PASSWD)\n\ttry:\n\t\temail_object.sendmail(EMAIL_ID, [message['To']], message.as_string())\n\t\temail_object.close()\n\texcept:\n\t\tpass","sub_path":"user_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"225405314","text":"# -*- coding: utf-8 -*-\n\nimport os, sys\nimport struct\nfrom collections import namedtuple\n\nFunction = namedtuple('Function', ['entry', 'end', 'name'])\nfunctions = dict()\nlabels = dict()\n\ndef get_registry_value(key, subkey, value):\n\timport _winreg\n\tkey = getattr(_winreg, key)\n\thandle = _winreg.OpenKey(key, subkey)\n\t(value, type) = _winreg.QueryValueEx(handle, value)\n\treturn value\n\ncputype = get_registry_value(\n\t\"HKEY_LOCAL_MACHINE\", \n\t\"HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\0\",\n\t\"ProcessorNameString\")\n\ncpuspeed = get_registry_value(\n\t\"HKEY_LOCAL_MACHINE\", \n\t\"HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\0\",\n\t\"~MHz\")\n\nclass TraceData:\n\tdef __init__(self, data, base_ts):\n\t\tself.data = data\n\t\tself.ts = (data['ts'] - base_ts)/(cpuspeed * 1000000.0)\n\n\tdef __repr__(self):\n\t\ts = ''\n\n\t\tif self.data['code'] == 0:\n\t\t\ts = 'trace'\n\t\t\n\t\ts = \"%.3f %s<%x>\" % (self.ts, s, self.data['thread'])\n\t\treturn s\n\n\tdef is_trace(self):\n\t\treturn self.data['code'] == 0\n\n\tdef get_count(self):\n\t\treturn self.data['count']\n\n\tdef unpack(self, start=0):\n\t\tlength = self.get_count() - start\n\t\tif length <= 0: return\n\t\t\n\t\tfor entry in struct.unpack_from('<%dI' % (length,), self.data['data'], start*4):\n\t\t\tyield entry\n\n\tdef get_trace(self, i):\n\t\td = struct.unpack('>2\n rotamer_trials_renew_taskpack(pose)\n minmover.apply(pose)\n pmm.apply(pose)\n if mc.boltzmann(pose):\n num_accepts+=1\n pmm.apply(pose)\n pack_mover_min_renew_taskpack(pose)\n jd.output_decoy(pose)\n \n'''# Acceptance Rate\n# log_acceptance_rate\nf=open('log.txt','a')\nacceptance_rate=float(num_accepts)/float(mc.total_trials())\nacceptance_rate=float('%.4f'%acceptance_rate)\nf.write('count \\t num_accepts \\t acceptance_rate \\n')\nf.write(str(count)+'\\t'+str( num_accepts)+'\\t\\t' +str(acceptance_rate)+'\\n')\nf.close()'''\n","sub_path":"PyRosetta/Code/1207movie.py","file_name":"1207movie.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"332448771","text":"import argparse\nimport os\nimport sys\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom matplotlib import pyplot as plt\nfrom torch.utils.data import DataLoader\nimport torch.optim as opt\nfrom tqdm import tqdm\nfrom transformers import BartTokenizer, get_linear_schedule_with_warmup\nimport datasets\nsys.path.insert(0, os.path.abspath('..'))\nfrom model.Seq2Seq import *\nfrom preprocessing.translation_data import *\n\nos.chdir('../')\n\narg_parser = argparse.ArgumentParser()\narg_parser.add_argument(\n '--gpu',\n type=int,\n default=0,\n help=f'Specify which gpu to use'\n)\n\narg_parser.add_argument(\n '-e', '--epoch',\n type=int,\n default=10,\n help=f'Specify number of training epochs'\n)\narg_parser.add_argument(\n '-b', '--batch',\n type=int,\n default=6,\n help=f'Specify batch size'\n)\nargs = arg_parser.parse_args()\n\n# device\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nif device == 'cuda':\n torch.cuda.set_device(args.gpu) # use an unoccupied GPU\n\n# hyperparameter\nNUM_EPOCH = args.epoch\nBATCH_SIZE = args.batch\nEMBEDDING_DIM = 128\nHIDDEN_DIM = 128\nNUM_LAYERS = 2\nDROPOUT = 0.1\n\n# model saving\nos.makedirs(os.path.dirname('model_weights' + '/'), exist_ok=True)\nMODEL_NAME = f'seq2seq_{BATCH_SIZE}'\nlog_file = open(os.path.join('model_weights', f'{MODEL_NAME}.log'), 'w')\nprint(f\"training seq2seq with batch size {BATCH_SIZE} for {NUM_EPOCH} epochs\")\n\n# model setup\ntokenizer = BartTokenizer.from_pretrained('facebook/bart-base')\nmodel = Seq2Seq(embed_size=EMBEDDING_DIM,\n hidden_size=HIDDEN_DIM,\n num_layers=NUM_LAYERS,\n dropout=DROPOUT).to(device)\noptimizer = opt.Adam(model.parameters())\n\n# record these for each epoch\nloss_record = []\nppl_record = []\n# training loop\nfor epo in range(NUM_EPOCH):\n model.train()\n total_loss = 0\n\n '''\n DataLoader\n '''\n dataset = TranslationData(data='train')\n data_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=BATCH_SIZE,\n shuffle=True\n )\n\n # training\n train_iterator_with_progress = tqdm(data_loader)\n idx = 0\n for batch in train_iterator_with_progress:\n try:\n # input encoding\n input_encoding = tokenizer(batch['en'], return_tensors='pt', padding=True, truncation=True)\n input_ids = input_encoding['input_ids']\n input_ids = torch.transpose(input_ids, 0, 1).to(device) # shape: (input_len, batch_size)\n\n # target encoding\n target_encoding = tokenizer(batch['de'], return_tensors='pt', padding=True, truncation=True)\n target_ids = target_encoding['input_ids']\n target_ids = torch.transpose(target_ids, 0, 1).to(device) # shape: (target_len, batch_size)\n\n # zero-out gradient\n optimizer.zero_grad()\n\n # forward pass\n outputs, _ = model(x=input_ids, y=target_ids) # outputs.shape: (target_len, batch_size, vocab_size)\n\n # prepare labels for cross entropy by removing the first time stamp ()\n labels = target_ids[1:, :] # shape: (target_len - 1, batch_size)\n labels = labels.reshape(-1).to(device) # shape: ((target_len - 1) * batch_size)\n\n # prepare model predicts for cross entropy by removing the last timestamp and merge first two axes\n outputs = outputs[:-1, ...] # shape: (target_len - 1, batch_size, vocab_size)\n outputs = outputs.reshape(-1, outputs.shape[-1]).to(device)\n # shape: ((target_len - 1) * batch_size, vocab_size)\n\n # compute loss and perform a step\n criterion = nn.CrossEntropyLoss(ignore_index=1) # ignore padding index\n loss = criterion(outputs, labels)\n\n loss.backward()\n\n torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1) # gradient clipping\n optimizer.step()\n # scheduler.step()\n\n # if idx % 1000 == 0:\n # print(f'epoch: {epo}, batch: {idx}, memory reserved {torch.cuda.memory_reserved(DEVICE_ID) / 1e9} GB')\n # print(f'epoch: {epo}, batch: {idx}, memory allocated {torch.cuda.memory_allocated(DEVICE_ID) / 1e9} GB')\n idx += 1\n\n total_loss += float(loss)\n train_iterator_with_progress.set_description(f'Epoch {epo}')\n train_iterator_with_progress.set_postfix({'Loss': loss.item()})\n except Exception as e:\n print(e)\n\n loss_record.append(total_loss)\n print(f'Loss in epoch {epo}: {total_loss}')\n log_file.write(f'Epoch:{epo} ')\n log_file.write(f'Loss:{total_loss} ')\n\n # evaluation\n model.eval()\n with torch.no_grad():\n '''\n DataLoader\n '''\n valid_dataset = TranslationData(data='test')\n valid_data_loader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size=BATCH_SIZE,\n shuffle=True\n )\n\n batch_num = 0\n total_loss = 0\n metric_bleu = datasets.load_metric('sacrebleu')\n for batch in valid_data_loader:\n # input encoding\n input_encoding = tokenizer(batch['en'], return_tensors='pt', padding=True, truncation=True)\n input_ids = input_encoding['input_ids']\n input_ids = torch.transpose(input_ids, 0, 1).to(device) # shape: (input_len, batch_size)\n\n # target encoding\n target_encoding = tokenizer(batch['de'], return_tensors='pt', padding=True, truncation=True)\n target_ids = target_encoding['input_ids']\n target_ids = torch.transpose(target_ids, 0, 1).to(device) # shape: (target_len, batch_size)\n\n # forward pass\n outputs, _ = model(x=input_ids, y=target_ids) # outputs.shape: (target_len, batch_size, vocab_size)\n\n # prepare labels for cross entropy by removing the first time stamp ()\n labels = target_ids[1:, :] # shape: (target_len - 1, batch_size)\n labels = labels.reshape(-1).to(device) # shape: ((target_len - 1) * batch_size)\n\n # prepare model predicts for cross entropy by removing the last timestamp and merge first two axes\n outputs = outputs[:-1, ...] # shape: (target_len - 1, batch_size, vocab_size)\n outputs = outputs.reshape(-1, outputs.shape[-1]).to(device)\n # shape: ((target_len - 1) * batch_size, vocab_size)\n\n # compute loss and perform a step\n criterion = nn.CrossEntropyLoss(ignore_index=1) # ignore padding index\n loss = criterion(outputs, labels)\n\n total_loss += float(loss)\n batch_num += 1\n\n input_ids = torch.transpose(input_ids, 0, 1).to(device)\n model_res_ids = []\n for source in input_ids:\n length = torch.sum(source != 1)\n model_res_ids.append(model.generate(source.reshape(-1, 1)[:length]))\n predictions = [tokenizer.decode(g, skip_special_tokens=True) for g in model_res_ids]\n\n tmp_predictions, tmp_targets = [], []\n for prediction, target in zip(predictions, batch['de']):\n if len(target) > 0:\n tmp_predictions.append(prediction)\n tmp_targets.append(target)\n predictions, targets = tmp_predictions, tmp_targets\n references = [[r] for r in targets]\n metric_bleu.add_batch(predictions=predictions, references=references)\n\n perplexity = np.exp(total_loss / batch_num)\n ppl_record.append(perplexity)\n score_bleu = metric_bleu.compute()\n print(f'Perplexity: {perplexity}')\n print(f'BLEU: {round(score_bleu[\"score\"], 1)} out of {round(100., 1)}')\n log_file.write(f'Perplexity:{perplexity}')\n log_file.write(f'BLEU: {round(score_bleu[\"score\"], 1)} out of {round(100., 1)}\\n')\n\n SAVE_PATH = os.path.join('model_weights', f'{MODEL_NAME}_epoch_{epo+1}.pt')\n # save model after training for one epoch\n torch.save(model.state_dict(), SAVE_PATH)\n\n# close log file\nlog_file.close()\n\n# plot loss and ppl\nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))\n\nepochs = list(range(NUM_EPOCH))\nax[0].plot(epochs, loss_record)\nax[0].set_title('Loss', fontsize=20)\nax[0].set_xlabel('Epoch', fontsize=15)\nax[0].set_ylabel('Loss', fontsize=15)\n\nax[1].plot(epochs, ppl_record)\nax[1].set_title('Perplexity', fontsize=20)\nax[1].set_xlabel('Epoch', fontsize=15)\nax[1].set_ylabel('Perplexity', fontsize=15)\n\nos.makedirs(os.path.dirname('figures' + '/'), exist_ok=True)\nfig.savefig(os.path.join('figures', f'{MODEL_NAME}'))\n\n\n","sub_path":"train/train_seq2seq.py","file_name":"train_seq2seq.py","file_ext":"py","file_size_in_byte":8597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"619607024","text":"from typing import List, Mapping, Optional\n\nfrom app.data_models.answer_store import AnswerStore\nfrom app.data_models.list_store import ListStore\nfrom app.data_models.progress_store import ProgressStore\nfrom app.questionnaire.location import Location\nfrom app.questionnaire.questionnaire_schema import QuestionnaireSchema\nfrom app.questionnaire.routing_path import RoutingPath\nfrom app.questionnaire.rules import (\n evaluate_goto,\n evaluate_skip_conditions,\n is_goto_rule,\n)\n\n\nclass PathFinder:\n def __init__(\n self,\n schema: QuestionnaireSchema,\n answer_store: AnswerStore,\n list_store: ListStore,\n progress_store: ProgressStore,\n metadata: Mapping,\n ):\n self.answer_store = answer_store\n self.metadata = metadata\n self.schema = schema\n self.progress_store = progress_store\n self.list_store = list_store\n\n def routing_path(\n self, section_id: str, list_item_id: Optional[str] = None\n ) -> RoutingPath:\n \"\"\"\n Visits all the blocks in a section and returns a path given a list of answers.\n \"\"\"\n blocks: List[Mapping] = []\n routing_path_block_ids = []\n current_location = Location(section_id=section_id, list_item_id=list_item_id)\n section = self.schema.get_section(section_id)\n list_name = self.schema.get_repeating_list_for_section(\n current_location.section_id\n )\n\n if section:\n for group in section[\"groups\"]:\n if \"skip_conditions\" in group:\n if evaluate_skip_conditions(\n group[\"skip_conditions\"],\n self.schema,\n self.metadata,\n self.answer_store,\n self.list_store,\n current_location=current_location,\n ):\n continue\n\n blocks.extend(group[\"blocks\"])\n\n if blocks:\n routing_path_block_ids = self._build_routing_path_block_ids(\n blocks, current_location\n )\n\n return RoutingPath(routing_path_block_ids, section_id, list_item_id, list_name)\n\n @staticmethod\n def _block_index_for_block_id(blocks, block_id):\n return next(\n (index for (index, block) in enumerate(blocks) if block[\"id\"] == block_id),\n None,\n )\n\n def _build_routing_path_block_ids(self, blocks, current_location):\n # Keep going unless we've hit the last block\n routing_path_block_ids = []\n block_index = 0\n repeating_list = self.schema.get_repeating_list_for_section(\n current_location.section_id\n )\n\n while block_index < len(blocks):\n block = blocks[block_index]\n\n is_skipping = block.get(\"skip_conditions\") and evaluate_skip_conditions(\n block[\"skip_conditions\"],\n self.schema,\n self.metadata,\n self.answer_store,\n self.list_store,\n current_location=current_location,\n routing_path_block_ids=routing_path_block_ids,\n )\n\n if not is_skipping:\n block_id = block[\"id\"]\n if repeating_list and current_location.list_item_id:\n this_location = Location(\n section_id=current_location.section_id,\n block_id=block_id,\n list_name=repeating_list,\n list_item_id=current_location.list_item_id,\n )\n else:\n this_location = Location(\n section_id=current_location.section_id, block_id=block_id\n )\n\n if block_id not in routing_path_block_ids:\n routing_path_block_ids.append(block_id)\n\n # If routing rules exist then a rule must match (i.e. default goto)\n routing_rules = block.get(\"routing_rules\")\n if routing_rules:\n block_index = self._evaluate_routing_rules(\n this_location,\n blocks,\n routing_rules,\n block_index,\n routing_path_block_ids,\n )\n if block_index:\n continue\n\n return routing_path_block_ids\n\n # Last block so return routing_path_block_ids\n if block_index == len(blocks) - 1:\n return routing_path_block_ids\n\n # No routing rules, so step forward a block\n block_index = block_index + 1\n\n def _evaluate_routing_rules(\n self, this_location, blocks, routing_rules, block_index, routing_path_block_ids\n ):\n for rule in filter(is_goto_rule, routing_rules):\n should_goto = evaluate_goto(\n rule[\"goto\"],\n self.schema,\n self.metadata,\n self.answer_store,\n self.list_store,\n current_location=this_location,\n routing_path_block_ids=routing_path_block_ids,\n )\n\n if should_goto:\n if rule[\"goto\"].get(\"section\") == \"End\":\n return None\n\n next_block_id = self._get_next_block_id(rule)\n next_block_index = PathFinder._block_index_for_block_id(\n blocks, next_block_id\n )\n next_precedes_current = (\n next_block_index is not None and next_block_index < block_index\n )\n\n if next_precedes_current:\n self._remove_rule_answers(rule[\"goto\"], this_location)\n routing_path_block_ids.append(next_block_id)\n return None\n\n return next_block_index\n\n def _get_next_block_id(self, rule):\n if \"group\" in rule[\"goto\"]:\n return self.schema.get_first_block_id_for_group(rule[\"goto\"][\"group\"])\n return rule[\"goto\"][\"block\"]\n\n def _remove_rule_answers(self, goto_rule, this_location):\n # We're jumping backwards, so need to delete all answers from which\n # route is derived. Need to filter out conditions that don't use answers\n if \"when\" in goto_rule.keys():\n for condition in goto_rule[\"when\"]:\n if \"meta\" not in condition.keys():\n self.answer_store.remove_answer(condition[\"id\"])\n\n self.progress_store.remove_completed_location(location=this_location)\n","sub_path":"app/questionnaire/path_finder.py","file_name":"path_finder.py","file_ext":"py","file_size_in_byte":6677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"427077370","text":"import os\nfrom functools import reduce\nfrom configparser import ConfigParser\nfrom urllib.parse import urlparse\n\nimport dataset\nimport requests\nimport html2text\nimport progressbar\nfrom readability import Document\n\nPATH_DATA_BROWSER = os.path.join(os.environ['HOME'],\n '.mozilla/firefox/')\n\n\nclass BrowserWorker:\n def __init__(self, browser_path=None, tag='read later'):\n self.browser_path = browser_path\n self.tag = tag\n\n def profile_path(self):\n profile_ini = os.path.join(self.browser_path, 'profiles.ini')\n\n if not os.path.isfile(profile_ini):\n raise Exception('File does not exist <{file_path}>'\n .format(file_path=profile_ini))\n\n profiles = ConfigParser()\n profiles.read(profile_ini)\n\n profile_abs_path = None\n\n for profile in profiles._sections:\n _prof = profiles._sections.get(profile)\n if 'default' in _prof.keys() and _prof.get('default') is '1':\n profile_abs_path = _prof['path']\n break\n\n if not profile_abs_path:\n raise Exception('No profile found <{file_path}>'\n .format(file_path=profile_ini))\n\n return os.path.join(self.browser_path, profile_abs_path,\n 'places.sqlite')\n\n def _tags(self):\n places_sqlite = self.profile_path()\n data = dataset.connect('sqlite:///{}'.format(places_sqlite))\n\n return data['moz_bookmarks'].distinct('id', 'title', type=2, parent=4)\n\n def _tag_by_label(self, label=None):\n tags = [dict(tag).get('id')\n for tag in self._tags() if tag['title'] == label]\n\n tag_id = None\n if tags and len(tags) is 1:\n tag_id = tags[0]\n\n return tag_id\n\n def articles(self):\n places_sqlite = self.profile_path()\n data = dataset.connect('sqlite:///{}'.format(places_sqlite))\n\n tag_id = self._tag_by_label('read later')\n articles_key = [article for article in data['moz_bookmarks'].distinct('fk', parent=tag_id)]\n\n articles = [list(data['moz_places'].distinct('url',\n id=article.get('fk')))[0]['url']\n for article in articles_key]\n return articles\n\n\ndef article_folder_archive(file_title):\n\n archive_folder = os.path.join(os.environ.get('HOME'), 'Documents',\n 'Archive')\n if not os.path.isdir(archive_folder):\n os.makedirs(archive_folder)\n\n return os.path.join(archive_folder, file_title)\n\n\ndef articles():\n data_articles = BrowserWorker(PATH_DATA_BROWSER)\n articles = data_articles.articles()\n\n for article_url in progressbar.progressbar(articles):\n url = urlparse(article_url)\n response = requests.get(article_url)\n doc = Document(response.text)\n article_markdown = html2text.html2text(doc.summary())\n\n\n file_title = '{}.md'.format(url.path.split('/')[-1])\n file_save = article_folder_archive(file_title)\n with open(file_save, 'a') as article_file:\n article_file.write(article_markdown)\n\nif __name__ == '__main__':\n articles()\n","sub_path":"readings.py","file_name":"readings.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651720691","text":"from tkinter import *\r\n\r\nroot = Tk()\r\nroot.title(\"Опрос\")\r\nroot.geometry(\"720x800\")\r\n\r\n\r\n\r\n\r\nbtn = Button(text=\"Посмотреть результаты\", # текст кнопки\r\n background=\"#555\", # фоновый цвет кнопки\r\n foreground=\"#ccc\", # цвет текста\r\n padx=\"20\", # отступ от границ до содержимого по горизонтали\r\n pady=\"8\", # отступ от границ до содержимого по вертикали\r\n font=\"16\") # высота шрифта\r\nbtn.pack(side=BOTTOM, padx=0, pady=50)\r\nlabel1 = Label(text=\"Какой язык программирования вам больше всего нравится ?\")\r\nlabel1.pack(side=TOP,padx=0,pady=10)\r\nPossible_answer = IntVar()\r\n\r\npython_checkbutton = Radiobutton(text=\"Java\",variable=Possible_answer, value=1, padx=15, pady=10)\r\npython_checkbutton.pack(side=TOP,padx=0,pady=10)\r\npython_checkbutton = Radiobutton(text=\"Python\",variable=Possible_answer, value=2, padx=15, pady=10)\r\npython_checkbutton.pack(side=TOP,padx=0,pady=10)\r\n\r\nlabel1 = Label(text=\"Какой язык программирования вам больше всего нравится ?\")\r\nlabel1.pack(side=TOP,padx=0,pady=10)\r\nanswer = IntVar()\r\n\r\npython_checkbutton = Radiobutton(text=\"Java\",variable=answer, value=3, padx=15, pady=10)\r\npython_checkbutton.pack(side=TOP,padx=0,pady=10)\r\npython_checkbutton = Radiobutton(text=\"Python\",variable=answer, value=4, padx=15, pady=10)\r\npython_checkbutton.pack(side=TOP,padx=0,pady=10)\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()","sub_path":"pythonProject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"256384715","text":"with open('action.csv', 'r') as input_item:\n lines = input_item.readlines()\n\nnew_lines = []\nfor line in lines:\n items = line.split(\"_!_\") # 22780_!_611_!_2_!_0_!_1617488831_!_1\n # 250def1d50bf_!_1690341_!_1621319827_!_1_!_0_!_1\n new_line = [items[0], items[1], items[4], items[2], items[3], items[5]]\n new_lines.append(\"_!_\".join(new_line))\n\nwith open('action_2.csv', 'w') as out:\n out.writelines(new_lines)\n","sub_path":"src/offline/movie/data-scraping/filter_movie.py","file_name":"filter_movie.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"344865293","text":"# -*- coding: utf-8 -*-\n\nfrom geoalchemy2.elements import _SpatialElement\n\nfrom pyramid_oereb.lib import b64\nfrom pyramid_oereb.lib.records.image import ImageRecord\nfrom pyramid_oereb.lib.sources import BaseDatabaseSource\nfrom geoalchemy2.shape import to_shape\n\nfrom pyramid_oereb.lib.sources.municipality import MunicipalityBaseSource\n\n\nclass DatabaseSource(BaseDatabaseSource, MunicipalityBaseSource):\n\n def read(self, params, fosnr=None):\n \"\"\"\n Central method to read a municipality by it's id_bfs identifier.\n\n Args:\n params (pyramid_oereb.views.webservice.Parameter): The parameters of the extract request.\n fosnr (int or None): The federal number of the municipality defined by the statistics office.\n \"\"\"\n session = self._adapter_.get_session(self._key_)\n try:\n self.records = list()\n if fosnr:\n results = session.query(self._model_).filter(self._model_.fosnr == fosnr).all()\n else:\n results = session.query(self._model_).all()\n for result in results:\n logo = ImageRecord(b64.decode(result.logo))\n self.records.append(self._record_class_(\n result.fosnr,\n result.name,\n result.published,\n logo,\n geom=to_shape(result.geom).wkt if isinstance(\n result.geom, _SpatialElement) else None,\n ))\n finally:\n session.close()\n","sub_path":"pyramid_oereb/standard/sources/municipality.py","file_name":"municipality.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"200042469","text":"from schema import Schema\n\nschema = Schema(\n {\n \"userId\": str,\n \"paymentMethod\": str,\n \"total\": str,\n \"product\": [{\"id\": str, \"type\": str, \"name\": str, \"price\": str}],\n },\n ignore_extra_keys=True,\n)\n\ndef validate(event):\n return schema.validate(event)","sub_path":"src/order/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"302667538","text":"import dropbox\r\n\r\nclass TransferData:\r\n def __init__(self, access_token):\r\n self.access_token=access_token\r\n\r\n def upload(self, file_from,file_to):\r\n db=dropbox.Dropbox(self.access_token)\r\n\r\n f=open(file_from,'rb')\r\n db.files_upload(f.read(), file_to)\r\n\r\ndef main():\r\n access_token=\"JhbcWnh-C6cAAAAAAAAAAT70P7DuQoK_-rbd5DKTvTAdqMql-uFFmm-cppm-mIxy\"\r\n TransferData(access_token)\r\n\r\n file_from=input(\"Enter the file path to transfer: \")\r\n file_to=input(\"Enter the full file path to transfer: \")\r\n\r\n TransferData.upload(file_from,file_to)\r\n print(\"File has been moved.\")\r\n\r\n \r\n\r\n","sub_path":"dropbox.py","file_name":"dropbox.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"344818669","text":"import time\r\nimport sys\r\nimport colored\r\n#印出棋盤\r\ndef printBoard(board,width):\r\n print(\"\\t\",end=\"\")\r\n for i in range(size):\r\n print(str(i+1),end=\" \"*width)\r\n print(\"\\n\")#換兩行==print()print()\r\n for rowNum in range(size):\r\n print(str(rowNum+1),end=\"\\t\")\r\n for pieceNum in range(size):\r\n piece=board[rowNum][pieceNum]\r\n if piece==\"O\":\r\n THISfcolor=colored.fg(\"green\")\r\n elif piece==\"X\":\r\n THISfcolor=colored.fg(\"red_1\")\r\n elif piece==\".\":\r\n THISfcolor=fcolor\r\n print(THISfcolor+bcolor+piece+reset,end=\"\")\r\n if not pieceNum==size-1: #不是最後一個旗子\r\n print(fcolor+bcolor+\" \" * width+reset,end=\"\")\r\n print()\r\n\r\n #print(fcolor+bcolor+(\" \"*width).join(board[rowNum])+reset)\r\n\r\n print(\"\\t\"+fcolor+bcolor+\" \"*(width*(size-1)+size)+reset)\r\n#設定棋盤大小\r\ndef setSize():\r\n print(\"plz enter the size of board.(n in size(nxn))(allowed size=5 to 20)\")\r\n while True:\r\n a=input()\r\n try:\r\n a=int(a)\r\n except ValueError:\r\n print(\"not num!\")\r\n continue\r\n if a>20:\r\n print(\"too BIG!!!\")\r\n continue\r\n elif a<5:\r\n print(\"too SMALL!!!\")\r\n continue\r\n return a\r\n#清空畫面(感謝徐晧倫)\r\ndef clear():\r\n for i in range(100):\r\n print()\r\n#玩家下棋\r\ndef player():\r\n print(\"plz enter ur pos.\")\r\n while True:\r\n a=input()\r\n if a.find(\" \")==-1 or len(a) > 5:\r\n print(\"wrong!!\")\r\n continue\r\n try:\r\n x,y = [int(i)-1 for i in a.split()]\r\n except ValueError:\r\n print(\"not num!\")\r\n continue\r\n #x,y=====0~size-1\r\n if x<0 or y<0 or x>size-1 or y>size-1:\r\n print(\"UR WEIRD NUM NOT ALLOWED!!!\")\r\n continue\r\n if not checkNoPiece(y,x):\r\n print(\"There is already a piece.\")\r\n continue\r\n break\r\n board[y][x]=\"O\"\r\n#檢查是否下在沒棋子之處\r\ndef checkNoPiece(y,x):\r\n return board[y][x]==\".\"\r\n#檢查棋盤是否已滿\r\ndef checkBoardFull(board):\r\n isFull = True\r\n for row in board:\r\n for piece in row:\r\n if piece==\".\":\r\n isFull=False\r\n return isFull\r\n#以minimax搜索最佳下棋位置\r\ndef DeepCheck(checkDepth,onlyCheck):\r\n \r\n if checkBoardFull(board):\r\n gameover(\"tie\")\r\n\r\n positionsss=dict()\r\n depth=0\r\n newBoard=[[i for i in row] for row in board]\r\n positionsss=AllCheck(\"AI\",depth,newBoard,checkDepth,onlyCheck,0,False)\r\n return positionsss\r\n#檢查一層的所有可下棋位置\r\ndef AllCheck(who,depth,newBoard,checkDepth,onlyCheck,alpha,checkAplhaBeta):\r\n cut=False\r\n beta=\"no\"\r\n positions=dict()\r\n #所有可下棋位置\r\n for y in range(size):\r\n for x in range(size):\r\n if newBoard[y][x]==\".\":\r\n #計算下在各格的分數\r\n score=check(x,y,positions,who,depth,checkDepth,newBoard,onlyCheck,beta,beta!=\"no\")\r\n #存入dictionary\r\n positions[score]=(y,x)\r\n #存較大層之最大or最小分數\r\n if who==\"AI\":\r\n beta=max(positions.keys())\r\n elif who==\"playerAI\":\r\n beta=min(positions.keys())\r\n #alpha-beta剪枝\r\n if checkAplhaBeta:\r\n if who==\"AI\" and beta>alpha and checkAplhaBeta:\r\n cut=True\r\n break\r\n elif who==\"playerAI\" and beta=checkDepth:\r\n return pos\r\n else:\r\n return AllCheck(\"AI\",depth+1,aWholeNewBoard,checkDepth,onlyCheck,beta,checkAplhaBeta)\r\n elif who==\"AI\":\r\n if end or checkBoardFull(aWholeNewBoard) or depth+1>=checkDepth:\r\n return pos\r\n else:\r\n return AllCheck(\"playerAI\",depth+1,aWholeNewBoard,checkDepth,onlyCheck,beta,checkAplhaBeta)\r\n\r\n#直排\r\ndef vertical(b,pos,who,depth,onlyCheck):\r\n for x in range(size):\r\n line = [b[y][x] for y in range(size)]\r\n piecePos=[(y,x) for y in range(size)]\r\n try:\r\n line = \"\".join(line)\r\n except:\r\n print(\"sdszdsd\")\r\n\r\n pos,end=analyze(line,b,piecePos,pos,who,depth,onlyCheck)\r\n return pos,end\r\n#橫排\r\ndef horizontal(b,pos,who,depth,onlyCheck):\r\n for y in range(size):\r\n line = [b[y][x] for x in range(size)]\r\n piecePos=[(y,x) for x in range(size)]\r\n try:\r\n line = \"\".join(line)\r\n except:\r\n print(\"sdszdsd\")\r\n\r\n pos,end=analyze(line,b,piecePos,pos,who,depth,onlyCheck)\r\n return pos,end\r\n#斜排\r\ndef slideUP(b,pos,who,depth,onlyCheck):\r\n for k in range(0+4,(size*2-1)-4):\r\n line = [b[y][x] for x in range(size) for y in range(size) if x+y==k]\r\n piecePos=[(y,x) for x in range(size) for y in range(size) if x+y==k]\r\n try:\r\n line = \"\".join(line)\r\n except:\r\n print(\"sdszdsd\")\r\n \r\n pos,end=analyze(line,b,piecePos,pos,who,depth,onlyCheck)\r\n return pos,end\r\n#斜排\r\ndef slideDOWN(b,pos,who,depth,onlyCheck):\r\n for k in range((-(size-1))+4,(size)-4):\r\n line = [b[y][x] for x in range(size) for y in range(size) if x-y==k]\r\n piecePos=[(y,x) for x in range(size) for y in range(size) if x-y==k]\r\n try:\r\n line = \"\".join(line)\r\n except:\r\n print(\"sdszdsd\")\r\n\r\n pos,end=analyze(line,b,piecePos,pos,who,depth,onlyCheck)\r\n return pos,end\r\n#分析情勢再加減分數\r\ndef analyze(line,b,piecePos,pos,who,depth,onlyCheck):\r\n #playerAI = O AI = X\r\n \r\n\r\n s,e=\"X\",\"O\"\r\n\r\n\r\n how=(1/10)**depth#越下層之分數越接近0,較不會影響總分\r\n checkend=False\r\n\r\n #判斷情勢\r\n if e*5 in line:\r\n if depth==0 and onlyCheck:\r\n gameover(\"win\")#玩家贏了\r\n pos-=10000000000 * how\r\n print(\"too bad\")\r\n checkend=True\r\n if e*4 in line:\r\n start=line.find(e*4)-1\r\n end=start+5\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" or endPiece==\".\":\r\n pos-=10000000 * how\r\n\r\n \r\n if e*3 in line:\r\n start=line.find(e*3)-1\r\n end=start+4\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=1000000 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos-=5000 * how\r\n\r\n \r\n if e*2 in line:\r\n start=line.find(e*2)-1\r\n end=start+3\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=100 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos-=50 * how\r\n\r\n \r\n if e*1 in line:\r\n start=line.find(e*1)-1\r\n end=start+2\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=3 * how\r\n elif startPiece==\".\":\r\n pos-=1 * how\r\n elif endPiece==\".\":\r\n pos-=1 * how\r\n\r\n\r\n\r\n if s*5 in line:\r\n if depth==0 and onlyCheck:\r\n gameover(\"lose\")#AI贏了\r\n pos+=10000000000 * how\r\n print(\"too good\")\r\n checkend=True\r\n if s*4 in line:\r\n start=line.find(s*4)-1\r\n end=start+5\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos+=10000000 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos+=5000 * how\r\n\r\n \r\n if s*3 in line:\r\n start=line.find(s*3)-1\r\n end=start+4\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos+=1000 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos+=10 * how\r\n\r\n \r\n if s*2 in line:\r\n start=line.find(s*2)-1\r\n end=start+3\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos+=5 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos+=2 * how\r\n\r\n\r\n if s*1 in line:\r\n start=line.find(s*1)-1\r\n end=start+2\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos+=2 * how\r\n elif startPiece==\".\" or endPiece==\".\":\r\n pos+=1 * how\r\n\r\n\r\n\r\n\r\n if e+\".\"+e in line:\r\n start=line.find(e+\".\"+e)-1\r\n end=start+4\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=500000 * how\r\n elif startPiece==\".\":\r\n pos-=5000 * how\r\n elif endPiece==\".\":\r\n pos-=5000 * how\r\n\r\n\r\n\r\n\r\n \r\n if e+e+\".\"+e in line:\r\n start=line.find(e+e+\".\"+e)-1\r\n end=start+5\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=1000000 * how\r\n elif startPiece==\".\":\r\n pos-=10000 * how\r\n elif endPiece==\".\":\r\n pos-=10000 * how\r\n if e+\".\"+e+e in line:\r\n start=line.find(e+\".\"+e+e)-1\r\n end=start+5\r\n \r\n \r\n if start>=0:\r\n startPos=piecePos[start]\r\n startPiece=b[startPos[0]][startPos[1]]\r\n else:\r\n startPiece=\"N\"\r\n if end<=len(line)-1:\r\n endPos=piecePos[end]\r\n endPiece=b[endPos[0]][endPos[1]]\r\n else:\r\n endPiece=\"N\"\r\n \r\n if startPiece==\".\" and endPiece==\".\":\r\n pos-=1000000 * how\r\n elif startPiece==\".\":\r\n pos-=10000 * how\r\n elif endPiece==\".\":\r\n pos-=10000 * how\r\n if e+e+\".\"+e+e in line:\r\n\r\n \r\n pos-=10000000 * how\r\n if e+e+e+\".\"+e in line:\r\n \r\n pos-=10000000 * how\r\n if e+\".\"+e+e+e in line:\r\n\r\n \r\n pos-=10000000 * how\r\n\r\n\r\n\r\n\r\n return pos,checkend\r\n#AI下棋\r\ndef ai(positions,board):\r\n if positions!=dict():\r\n besty,bestx=positions[max(positions.keys())]\r\n\r\n board[besty][bestx]=\"X\"\r\n\r\n else:\r\n print(\"the AI of this game is too stupid to decide where to place its pawn.\")\r\n print(\"So it's time for u to defeat it.\")\r\n return board\r\n#遊戲結束\r\ndef gameover(text):\r\n if text==\"win\":\r\n print(\"U win!!!\")\r\n elif text==\"lose\":\r\n print(\"haha u lose!!!\")\r\n elif text==\"tie\":\r\n print(\"the board is full!!!\")\r\n print(\"LOOK WHAT U'VE DONE!!!\")\r\n time.sleep(5)\r\n print(\"end!\")\r\n sys.exit()#end script\r\n\r\n\r\n#初始化\r\nsize=setSize()\r\nCheckDepth=1\r\n\r\nboard=[[\".\" for i in range(size)] for i in range(size)]\r\nboardWidth=3\r\nfcolor=colored.fg(\"black\")\r\nbcolor=colored.bg(\"white\")\r\nreset=colored.attr(\"reset\")\r\nboardSpaceAmount=size**2\r\nprint(f\"boardSpaceAmount:{boardSpaceAmount}\")\r\nprintBoard(board,boardWidth)\r\n#循環進行遊戲\r\nwhile 1:\r\n #玩家下棋\r\n player()\r\n boardSpaceAmount-=1\r\n printBoard(board,boardWidth)\r\n positions=DeepCheck(1,True)\r\n \r\n\r\n \r\n #訂定AI搜尋深度\r\n CheckDepth=int(-0.05 * boardSpaceAmount +7)#or+6\r\n print(f\"CheckDepth : {CheckDepth}\")\r\n #AI下棋\r\n print(\"loading...\")\r\n positions=DeepCheck(CheckDepth,False)\r\n clear()\r\n board=ai(positions,board)\r\n boardSpaceAmount-=1\r\n printBoard(board,boardWidth)\r\n positions=DeepCheck(1,True)\r\n","sub_path":"minimax_fixed.py","file_name":"minimax_fixed.py","file_ext":"py","file_size_in_byte":16812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"467557233","text":"import reframe as rfm\nimport reframe.utility.sanity as sn\n\n\n@rfm.required_version('>=2.14')\n@rfm.parameterized_test(\n ['dom', 'PrgEnv-gnu', 'gcc/7.3.0'],\n ['dom', 'PrgEnv-gnu', 'gcc/8.3.0'],\n ['dom', 'PrgEnv-intel', 'intel/18.0.2.199'],\n ['dom', 'PrgEnv-intel', 'intel/19.0.1.144'],\n ['dom', 'PrgEnv-cray', 'cce/8.7.10'],\n # \n ['daint', 'PrgEnv-gnu', 'gcc/4.9.3'],\n ['daint', 'PrgEnv-gnu', 'gcc/5.3.0'],\n ['daint', 'PrgEnv-gnu', 'gcc/6.2.0'],\n ['daint', 'PrgEnv-gnu', 'gcc/7.3.0'],\n ['daint', 'PrgEnv-intel', 'intel/17.0.4.196'],\n ['daint', 'PrgEnv-intel', 'intel/18.0.2.199'],\n ['daint', 'PrgEnv-cray', 'cce/8.6.1'],\n ['daint', 'PrgEnv-cray', 'cce/8.7.4'],\n ['daint', 'PrgEnv-pgi', 'pgi/17.5.0'],\n ['daint', 'PrgEnv-pgi', 'pgi/18.5.0'],\n ['daint', 'PrgEnv-pgi', 'pgi/18.10.0'],\n)\nclass SphExaMiniAppSquarepatch(rfm.CompileOnlyRegressionTest):\n \"\"\"\n cd sph-exa_mini-app.git/scripts/reframe/\n reframe --system dom:mc --exec-policy=async --keep-stage-files \\\n --prefix=$SCRATCH/reframe/ -r -c ./miniapp.py\n \"\"\"\n def __init__(self, sysname, prgenv, compilerversion):\n super().__init__()\n self.name = 'sphexa_' + sysname + \"_\" + compilerversion.replace('/', '')\n self.descr = 'compilation only check'\n self.valid_systems = ['%s:gpu' % sysname, '%s:mc' % sysname]\n self.valid_prog_environs = [prgenv]\n self.modules = [compilerversion]\n self.prgenv_flags = {\n 'PrgEnv-gnu': ['-I./include', '-std=c++14', '-O3', '-g',\n '-fopenmp', '-D_JENKINS'],\n 'PrgEnv-intel': ['-I./include', '-std=c++14', '-O3', '-g',\n '-qopenmp', '-D_JENKINS'],\n 'PrgEnv-cray': ['-I./include', '-hstd=c++14', '-O3', '-g',\n '-homp', '-D_JENKINS'],\n 'PrgEnv-pgi': ['-I./include', '-std=c++14', '-O3', '-g',\n '-mp', '-D_JENKINS'],\n }\n self.variables = {\n 'CRAYPE_LINK_TYPE': 'dynamic'\n }\n self.build_system = 'SingleSource'\n self.testname = 'sqpatch'\n self.sourcepath = '%s.cpp' % self.testname\n self.executable = '%s.exe' % self.testname\n self.rpt = '%s.rpt' % self.testname\n self.maintainers = ['JG']\n self.tags = {'pasc'}\n self.postbuild_cmd = ['file %s &> %s' % (self.executable, self.rpt)]\n self.sanity_patterns = sn.assert_found(\n 'ELF 64-bit LSB executable, x86-64', self.rpt)\n\n def setup(self, partition, environ, **job_opts):\n super().setup(partition, environ, **job_opts)\n environ_name = self.current_environ.name\n prgenv_flags = self.prgenv_flags[environ_name]\n self.build_system.cxxflags = prgenv_flags\n","sub_path":"scripts/reframe/miniapp.py","file_name":"miniapp.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"505453166","text":"from PyQt5.QtWidgets import QPushButton, QLineEdit, QRadioButton, QWidget, QGroupBox, QVBoxLayout, QDialogButtonBox, QLabel, QHBoxLayout\nfrom PyQt5.QtCore import pyqtSignal\n\n\nclass Editwidget(QWidget):\n sendCommand = pyqtSignal(str)\n\n def __init__(self, parent=None):\n super(Editwidget, self).__init__(parent)\n\n self.setGeometry(300, 300, 800, 600)\n self.max_time = QLineEdit(self)\n self.type_number = QRadioButton(\"Numer\", self)\n self.type_string = QRadioButton(\"Tekst\", self)\n self.max_input_size = QLineEdit(self)\n self.empty_input_yes = QRadioButton(\"Tak\", self)\n self.empty_input_no = QRadioButton(\"Nie\", self)\n self.hide_input_yes = QRadioButton(\"Tak\", self)\n self.hide_input_no = QRadioButton(\"Nie\", self)\n self.keyboard_edit_yes = QRadioButton(\"Tak\", self)\n self.keyboard_edit_no = QRadioButton(\"Nie\", self)\n self.barcode_reader_yes = QRadioButton(\"Tak\", self)\n self.barcode_reader_no = QRadioButton(\"Nie\", self)\n self.edit_field_title = QLineEdit(self)\n self.begin_value = QLineEdit(self)\n self.attributes_field = QLineEdit(self)\n self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(lambda: self.close())\n self.attributes_us_btn = QPushButton(\"US\")\n self.title_us_btn = QPushButton(\"US\")\n\n self.attributes_us_btn.clicked.connect(\n lambda: self.attributes_field.setText(self.attributes_field.text() + \"\\x1f\"))\n self.title_us_btn.clicked.connect(\n lambda: self.edit_field_title.setText(self.edit_field_title.text() + \"\\x1f\"))\n\n groupBox = QGroupBox()\n groupBox1 = QGroupBox()\n groupBox2 = QGroupBox()\n groupBox3 = QGroupBox()\n groupBox4 = QGroupBox()\n\n radio_layout = QVBoxLayout()\n radio_layout.addWidget(self.type_number)\n radio_layout.addWidget(self.type_string)\n\n radio_layout_label = QHBoxLayout()\n radio_layout_label.addLayout(radio_layout)\n radio_layout_label.addWidget(QLabel(\"Typ wprowadzanej wartości\"))\n groupBox.setLayout(radio_layout_label)\n\n radio_layout1 = QVBoxLayout()\n radio_layout1.addWidget(self.empty_input_yes)\n radio_layout1.addWidget(self.empty_input_no)\n\n radio_layout_label1 = QHBoxLayout()\n radio_layout_label1.addLayout(radio_layout1)\n radio_layout_label1.addWidget(QLabel(\"Wprowadzenie pustej wartości\"))\n groupBox1.setLayout(radio_layout_label1)\n\n radio_layout2 = QVBoxLayout()\n radio_layout2.addWidget(self.hide_input_yes)\n radio_layout2.addWidget(self.hide_input_no)\n\n radio_layout_label2 = QHBoxLayout()\n radio_layout_label2.addLayout(radio_layout2)\n radio_layout_label2.addWidget(QLabel(\"Maskowanie wprowadzanej treści\"))\n groupBox2.setLayout(radio_layout_label2)\n\n radio_layout3 = QVBoxLayout()\n radio_layout3.addWidget(self.keyboard_edit_yes)\n radio_layout3.addWidget(self.keyboard_edit_no)\n\n radio_layout_label3 = QHBoxLayout()\n radio_layout_label3.addLayout(radio_layout3)\n radio_layout_label3.addWidget(QLabel(\"Edycja z klawiatury\"))\n groupBox3.setLayout(radio_layout_label3)\n\n radio_layout4 = QVBoxLayout()\n radio_layout4.addWidget(self.barcode_reader_yes)\n radio_layout4.addWidget(self.barcode_reader_no)\n\n radio_layout_label4 = QHBoxLayout()\n radio_layout_label4.addLayout(radio_layout4)\n radio_layout_label4.addWidget(QLabel(\"Czytnik kodów kreskowych\"))\n groupBox4.setLayout(radio_layout_label4)\n\n row1 = QHBoxLayout()\n row1.addWidget(self.edit_field_title)\n row1.addWidget(self.title_us_btn)\n\n row3 = QHBoxLayout()\n row3.addWidget(self.attributes_field)\n row3.addWidget(self.attributes_us_btn)\n\n main_layout = QVBoxLayout()\n main_layout.addWidget(self.max_time)\n main_layout.addWidget(QLabel(\"Maksymalny czas trwania interakcji w sekundach (0 = bez limitu czasowego)\"))\n main_layout.addWidget(groupBox)\n main_layout.addWidget(self.max_input_size)\n main_layout.addWidget(QLabel(\"Maksymalny rozmiar wprowadzanej wartości\"))\n main_layout.addWidget(groupBox1)\n main_layout.addWidget(groupBox2)\n main_layout.addWidget(groupBox3)\n main_layout.addWidget(groupBox4)\n main_layout.addWidget(QLabel(\"Nazwa edytowalnego pola\"))\n main_layout.addLayout(row1)\n main_layout.addWidget(QLabel(\"Wartość początkowa pola edycyjnego\"))\n main_layout.addWidget(self.begin_value)\n main_layout.addWidget(QLabel(\"Dodatkowe atrybuty\"))\n main_layout.addLayout(row3)\n main_layout.addWidget(self.buttonBox)\n self.setLayout(main_layout)\n\n def accept(self):\n timeout = self.max_time.text()\n type_of_field = \"T\" if self.type_string.isChecked() else \"N\"\n max_size = self.max_input_size.text()\n empty = \"1\" if self.empty_input_yes.isChecked() else \"0\"\n mask = \"1\" if self.hide_input_yes.isChecked() else \"0\"\n keyboard = \"1\" if self.keyboard_edit_yes.isChecked() else \"0\"\n codereader = \"1\" if self.barcode_reader_yes.isChecked() else \"0\"\n title = self.edit_field_title.text()\n beginText = self.begin_value.text()\n attributes = self.attributes_field.text()\n print(self.edit_field_title.text())\n comm = f\"\\x1cK7\\x1c{timeout}\\x1c{type_of_field}\\x1c{max_size}\\x1c{empty}\\x1c{mask}\\x1c{keyboard}\\x1c{codereader}\\x1c{title}\\x1c{beginText}\\x1c{attributes}\\x03\"\n self.sendCommand.emit(comm)\n","sub_path":"editwidget.py","file_name":"editwidget.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"277640373","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 27 13:00:07 2022\r\n\r\n@author: youssef\r\n\"\"\"\r\n\r\nimport os\r\nos.environ['SNOPT_LICENSE'] = '/home/youssef/snopt/snopt7.lic'\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport floris.tools as wfct\r\nimport floris.tools.optimization.pyoptsparse as opt\r\nimport pdb\r\nfrom itertools import product, permutations\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef sort_boundaries(boundaries):\r\n bnd=pd.DataFrame(boundaries, columns=['x','y'])\r\n bnd.mean()\r\n A=np.degrees(np.arctan2(bnd.y-bnd.mean()[1],bnd.x-bnd.mean()[0]))\r\n A %= 360\r\n A.sort_values()\r\n boundaries=bnd.reindex(A.sort_values().index).values.tolist()\r\n return boundaries\r\n\r\n\r\ndef ConcentricCirclesLayout(N_circles,spc,D):\r\n spc=spc*D\r\n y_coordinates=np.array(0)\r\n x_coordinates=np.array(0)\r\n for i in range(N_circles):\r\n i=i+1\r\n N_turbines=math.floor(2*np.pi*i)\r\n angles=np.arange(0,2*np.pi,2*np.pi/N_turbines)\r\n x_coordinates=np.append(x_coordinates, i*spc*np.cos(angles))\r\n y_coordinates=np.append(y_coordinates, i*spc*np.sin(angles))\r\n x_coordinates=np.round(x_coordinates)\r\n y_coordinates=np.round(y_coordinates)\r\n layout= (x_coordinates.tolist(), y_coordinates.tolist())\r\n \r\n return layout\r\n\r\n\r\ndef SNOPTlayoutoptimization(fi,layout0,wd, ws, freq,plot):\r\n model = opt.layout.Layout(fi, boundaries, wdir=wd, wspd=ws, wfreq=freq)\r\n # optOptions={\"Major feasibility tolerance\": 1e-6, \"Verify level\": 3, \"Scale option\":2 ,\"Major optimality tolerance\": 5e-5}\r\n tmp = opt.optimization.Optimization(model=model, solver=\"SNOPT\") \r\n sol = tmp.optimize()\r\n if plot==1: \r\n model.plot_layout_opt_results(sol)\r\n plt.show() \r\n \r\n layout=(sol.getDVs()[\"x\"].tolist(),sol.getDVs()[\"y\"].tolist())\r\n \r\n return layout\r\n\r\ndef savelayout(layout,path,filename):\r\n layoutdf=pd.DataFrame(layout[0],columns=['x'])\r\n layoutdf['y']=layout[1]\r\n layoutdf.to_csv(path+filename, index=False)\r\n\r\n\r\n\r\n\r\n# Initialize the FLORIS interface fi\r\nfi = wfct.floris_interface.FlorisInterface(\"FLORIS_15MW.json\")\r\nD = fi.floris.farm.turbines[0].rotor_diameter\r\n\r\nN_circles=2\r\nspacing=5*D\r\nspc=5\r\nangles=np.arange(0,360,1)\r\nboundaries_x=np.round(N_circles*spacing*np.cos(np.radians(angles)))\r\nboundaries_y=np.round(N_circles*spacing*np.sin(np.radians(angles)))\r\nboundaries = [[x,y] for x, y in zip(boundaries_x, boundaries_y)]\r\nboundaries=sort_boundaries(boundaries)\r\nlayout0=ConcentricCirclesLayout(N_circles,spc,D) \r\n\r\nwd=[0., 22.5, 45., 67.5, 90., 112.5, 135., 157.5, 180., 202.5, 225., 247.5, 270., 292.5, 315., 337.5]\r\nws=[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]\r\nfreq= [.025, .024, .029, .036,.063, .065, .100, .122,.063, .038, .039, .083, .213, .046, .032, .022]\r\n\r\nfi.reinitialize_flow_field(layout_array=layout0)\r\nAEP_initial=fi.get_farm_AEP(np.array(wd), np.array(ws), np.array(freq)) * 1e-9\r\nprint(\"=====================================================\")\r\nprint('AEP_initial='+str(AEP_initial))\r\nprint(\"=====================================================\")\r\n\r\nlayout=SNOPTlayoutoptimization(fi,layout0,wd, ws, freq,1)\r\n\r\nfi.reinitialize_flow_field(layout_array=layout)\r\nAEP_optimized=fi.get_farm_AEP(np.array(wd), np.array(ws), np.array(freq)) * 1e-9\r\nprint(\"=====================================================\")\r\nprint('AEP_current='+str(AEP_optimized))\r\nprint(\"=====================================================\")\r\n\r\nsavelayout(layout,'','SNOPTlayoutnew.csv')","sub_path":"Linux_pyoptsparse/SNOPT_allwindfarm_fixed.py","file_name":"SNOPT_allwindfarm_fixed.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162931301","text":"#!/usr/bin/env python\n\nimport sys\nimport rospy\nfrom testmsgsrv.srv import *\nfrom testmsgsrv.msg import *\nfrom std_srvs.srv import Empty,EmptyResponse\nfrom threading import *\n\nclass Myclasss():\n\tdef __init__(self):\n\t\trospy.init_node('fibo_client_service', anonymous=True)\n\t\trospy.Subscriber('/action', fiboo, self.callback)\n\n\tdef babooo(self,x):\n\t\trospy.wait_for_service('get_fibonacci')\n\t\ttry:\n\t\t\tfff = rospy.ServiceProxy('get_fibonacci', Fibonaccii)\n\t\t\trespp = fff(x)\n\t\t\tprint(\"Final Fibonacci Series = %s\"%(str(respp.sequence)))\n\t\texcept rospy.ServiceException as e:\n\t\t\tprint(\"Service call failed: %s\"%e)\n\n\tdef callback(self,msg):\n\t\tprint(\"Feedback : Sequence : \",msg.sequence)\n\t\t# if eval(msg.sequence)[-1] == 144:\n\t\t# \tprint('asdfghjkl')\n\t\t# \tself.preempt()\n\n\tdef preempt(self):\n\t\trospy.wait_for_service('preempt_fibonacci')\n\t\ttry:\n\t\t\tfff = rospy.ServiceProxy('preempt_fibonacci', Empty)\n\t\t\trespp = fff()\n\t\texcept rospy.ServiceException as e:\n\t\t\tprint(\"Service call failed: %s\"%e)\n\n\nif __name__ == \"__main__\":\n\tx = sys.argv[1]\n\tobbject = Myclasss()\n\n\tt1 = Thread(target=obbject.babooo, args=(x,))\n\tt1.start()\n\n\tprint('threading success')\n","sub_path":"testmsgsrv/scripts/fibo_using_ROSserivce/fibo_client_service.py","file_name":"fibo_client_service.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"187590218","text":"_KNOWN_CLASSES = {\n 'HTTP': 'minemeld.ft.http.HttpFT',\n 'AggregatorIPv4': 'minemeld.ft.ipop.AggregateIPv4FT',\n 'Aggregator': 'minemeld.ft.op.AggregateFT',\n 'RedisSet': 'minemeld.ft.redis.RedisSet'\n}\n\n\ndef _dynamic_load(classname):\n if '.' not in classname:\n raise ValueError('invalid absolute classname %s' % classname)\n\n modname, classname = classname.rsplit('.', 1)\n t = __import__(modname, globals(), locals(), [classname])\n cls = getattr(t, classname)\n return cls\n\n\ndef factory(classname, name, chassis, config):\n classname = _KNOWN_CLASSES.get(classname, classname)\n\n return _dynamic_load(classname)(\n name=name,\n chassis=chassis,\n config=config\n )\n\n\nclass ft_states(object):\n READY = 0\n CONNECTED = 1\n REBUILDING = 2\n RESET = 3\n INIT = 4\n STARTED = 5\n CHECKPOINT = 6\n IDLE = 7\n STOPPED = 8\n","sub_path":"minemeld/ft/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"113088353","text":"# Entrypoint: com.google.android.apps.chrome.firstrun.FirstRunActivity.onCreate(Landroid/os/Bundle;)V\n# Target: invokevirtual < Application, Landroid/app/Activity, startActivity(Landroid/content/Intent;)V >@110\n\nIAAv0 = Real('IAAv0') # \nIAAv5 = Int('IAAv5') # Pointer<805177838>.this$0.access$100()\nIAAv8 = Int('IAAv8') # Pointer<805177838>.this$0.access$400().getFirstRunFlowComplete()\nIAAv1 = Int('IAAv1') # Pointer<582524242>.getBoolean()\nIAAv7 = Int('IAAv7') # Pointer<805177838>.this$0.access$500().checkAnyUserHasSeenToS()\nIAAv4 = Real('IAAv4') # Pointer<805177838>.mHasChildAccount\nIAAv2 = Int('IAAv2') # Pointer<-1202501681>.getInstance().checkHasChildAccount().SDK_INT\nIAAv6 = Int('IAAv6') # Pointer<805177838>.this$0.access$000()\nIAAv3 = Real('IAAv3') # Pointer<805177838>.mIsAndroidEduDevice\nIAAv9 = Real('IAAv9') # Pointer<805177838>.this$0.mObserver\n\ns.add(And(And(And(And(And(Or((IAAv0 == 0), (IAAv0 != 0)), (IAAv1 != 0)), (IAAv2 < 18)), And((IAAv3 != 0), (IAAv4 != 0))), And(And(Or(Or(And((IAAv5 == 0), (IAAv6 != 0)), And((IAAv5 == 0), (IAAv6 == 0))), (IAAv5 != 0)), (IAAv7 == 0)), (IAAv8 == 0))), Or((IAAv9 == 0), (IAAv9 != 0))))\n\n","sub_path":"static/playdrone/Reference_ref/com.android.chrome-2125114/constraints7_0.py","file_name":"constraints7_0.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"552733435","text":"import csv\n\ntimes = []\n# checks csv and turns everything into a float for calculations\ndef processCSV():\n with open('onsetimes.csv') as csvFile:\n reader = csv.reader(csvFile)\n for row in reader:\n timestring = str(row)\n timestring = timestring.replace(\"['\",\"\")\n timestring = timestring.replace(\"']\",\"\")\n timesint = float(timestring)\n times.append(timesint)\n\n# get between time\ndef getBetweenTime():\n btwtimes = []\n for i in times:\n try:\n timeindex1 = times.index(i)\n btwtime = times[timeindex1+1]-times[timeindex1]\n except IndexError:\n btwtime = 0\n btwtimes.append(str(btwtime)+\"F\")\n btwtimestr = str(btwtimes)\n btwtimestr = btwtimestr.replace(\"]\",\"\")\n btwtimestr = btwtimestr.replace(\"[\",\"\")\n btwtimestr = btwtimestr.replace(\"'\",\"\")\n return btwtimestr\n\nname = input(\"Name the script: \")\n# Copies header template onto the script and adds the times\ndef createTheScript():\n with open(\"unity3DScripts/SampleSongTemplateHeader.txt\") as template:\n with open(name+\".cs\", \"w\") as script:\n for line in template:\n script.write(line)\n script.write(\"public static float[] Times = {\"+str(getBetweenTime())+\"};}\")\n\n\n\n#functions\nprocessCSV()\ncreateTheScript()\n","sub_path":"_createScript.py","file_name":"_createScript.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162932830","text":"#\n# @lc app=leetcode id=35 lang=python3\n#\n# [35] Search Insert Position\n#\n# https://leetcode.com/problems/search-insert-position/description/\n#\n# algorithms\n# Easy (41.41%)\n# Likes: 1782\n# Dislikes: 214\n# Total Accepted: 512.8K\n# Total Submissions: 1.2M\n# Testcase Example: '[1,3,5,6]\\n5'\n#\n# Given a sorted array and a target value, return the index if the target is\n# found. If not, return the index where it would be if it were inserted in\n# order.\n# \n# You may assume no duplicates in the array.\n# \n# Example 1:\n# \n# \n# Input: [1,3,5,6], 5\n# Output: 2\n# \n# \n# Example 2:\n# \n# \n# Input: [1,3,5,6], 2\n# Output: 1\n# \n# \n# Example 3:\n# \n# \n# Input: [1,3,5,6], 7\n# Output: 4\n# \n# \n# Example 4:\n# \n# \n# Input: [1,3,5,6], 0\n# Output: 0\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n #Time Complexity: O(logn)\n #Space Complexity O(1)\n def searchInsert(self, nums, target):\n if not nums:\n return 0\n start = 0\n end = len(nums) - 1\n while start + 1 < end:\n mid = start + (end - start) // 2\n selected_ele = nums[mid]\n\n if selected_ele > target:\n end = mid\n elif selected_ele == target:\n return mid\n else:\n start = mid\n \n if target <= nums[start]:\n return start\n elif target <= nums[end]:\n return end\n else:\n return end + 1\n ","sub_path":"leetcode/Binary Search/35. Search Insert Position.py","file_name":"35. Search Insert Position.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"94879843","text":"from typing import Dict, Tuple, List\r\n\r\nEncodedStr = List[int]\r\nCodeToWordDict = Dict[int, str]\r\nWordToCodeDict = Dict[str, int]\r\n\r\n# Encapsulates the type for dictionary encoded text\r\nDictionaryEncoding = Tuple[CodeToWordDict, EncodedStr]\r\n\r\n\r\ndef dictionary_encode(text: str) -> DictionaryEncoding:\r\n \"\"\"\r\n Encodes a string of text using Dictionary Encoding\r\n :param text: The input string to encode\r\n :return: A tuple containing the dictionary of words by their ID,\r\n and a series of ID's which make up the original text\r\n \"\"\"\r\n # Calculate a word dictionary, and it's inverse,\r\n code_dict: CodeToWordDict = dict()\r\n word_dict: WordToCodeDict = dict()\r\n output_str: List[int] = []\r\n\r\n # Codes will be assigned as simple one-up numbers\r\n next_code: int = 0\r\n for word in text.split(\" \"):\r\n # If we haven't seen this word before, add it to the dictionary\r\n if word not in word_dict:\r\n code_dict[next_code] = word\r\n word_dict[word] = next_code\r\n next_code += 1\r\n\r\n # Lookup the code using our inverse dictionary\r\n code: int = word_dict.get(word)\r\n\r\n # Write the code to the output stream\r\n output_str.append(code)\r\n\r\n # Return the code dictionary and the output string.\r\n return code_dict, output_str\r\n\r\n\r\ndef dictionary_decode(encoded: DictionaryEncoding) -> str:\r\n \"\"\"\r\n Decode a dictionary encoded string into it's original form\r\n :param encoded: The dictionary encoded string\r\n :return: The original string\r\n \"\"\"\r\n # Read the parts of the encoded info\r\n input_dict, input_str = encoded\r\n\r\n # Convert the list of integers to a list of words, using the dictionary lookup\r\n output_chars = [input_dict.get(x) for x in input_str]\r\n\r\n # Join all the output words into a single string\r\n return \" \".join(output_chars)\r\n","sub_path":"CORE_DataRepresentation/DictionaryEncoding/dictionary_encode.py","file_name":"dictionary_encode.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"550167602","text":"import numpy as np\nfrom keras.applications.vgg16 import VGG16\nfrom scipy import misc\nimport pickle\nimport os\n\ntest_img_names = os.listdir('data/test')\ntrain_img_names = os.listdir('data/train')\n\ndef load_img(filename):\n img = misc.imread(filename)\n img = misc.imresize(img, size=(224,224,3))\n img = img/255\n return img\n\n#Load test and training images\ntest_imgs = [load_img(os.path.join('data/test', name)) for name in test_img_names]\ntest_imgs = np.stack(test_imgs)\n\ntrain_imgs = [load_img(os.path.join('data/train', name)) for name in train_img_names]\ntrain_imgs = np.stack(train_imgs)\n\nwith open('data/train_labels.pkl', 'rb') as f:\n train_labels = pickle.load(f)\n\n#Load the pretrained InceptionV3 model\nModel = vgg16(include_top=False, input_shape=(224, 224, 3), weights='imagenet')\n\nprint('loaded the model')\n\nfeaturized_train_data = Model.predict(train_imgs, verbose=1)\nfeaturized_test_data = Model.predict(test_imgs, verbose=1)\n\n#Save featurized images\nwith open('featurized_train_imgs.pkl', 'wb') as f:\n pickle.dump(featurized_train_data, f)\nwith open('featurized_test_imgs.pkl', 'wb') as f:\n pickle.dump(featurized_test_data, f)\n\n","sub_path":"featurize.py","file_name":"featurize.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"603174485","text":"import argparse\nimport os\nimport json\nimport fcntl\nimport errno\nimport subprocess\nimport time\nimport signal\n\n\nSIMULATE_TASK_RUNNER_KILLED = False\nSIMULATE_TASK_PROCESS_KILLED = False\nSIMULATE_SLOW_FINISH = False\n\nCONFIG_FILE = 'task_config.json'\n\nTASK_DIR = 'task'\n\nSTARTED_STATUS = 'STARTED'\nFINISHED_STATUS = 'FINISHED'\nBAD_STATUS = 'BAD'\n\n\ndef get_task_dir(task_id):\n return os.path.join(TASK_DIR, task_id)\n\n\ndef get_workers_path(task_id):\n return os.path.join(get_task_dir(task_id), 'workers')\n\n\ndef get_workers_lock(task_id):\n return os.path.join(get_task_dir(task_id), 'workers.lock')\n\n\ndef make_dir_exist(name):\n try:\n os.makedirs(name)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\ndef flock_nb(fd, operation):\n try:\n fcntl.flock(fd, operation | fcntl.LOCK_NB)\n return True\n except OSError as e:\n if e.errno not in [errno.EACCES, errno.EAGAIN]:\n raise\n else:\n return False\n\n\ndef pid_exists(pid):\n try:\n os.kill(pid, 0)\n except OSError as e:\n if e.errno == errno.ESRCH:\n return False\n if e.errno == errno.EPERM:\n # There's a process (probably), but access was denied\n return True\n raise\n return True\n\n\n\ndef readline(f, discard_newline=True):\n line = f.readline()\n if line.endswith('\\n'):\n return line[:-1]\n else:\n return line\n\n\nclass TaskRunner:\n def __init__(self, task_id, command, dependency_ids):\n self.task_id = task_id\n self.command = command\n self.dependency_ids = dependency_ids\n self.locked = False\n self.workers_lines = None\n self.workers_lock = None\n self.dep_workers_lines = None\n self.dep_workers_locks = {}\n self.bad_dep_workers = None\n\n def run(self, timeout=10, bad_dep_timeout=4, delay=0.05):\n \"\"\"\n timeout is the total timeout to verify statuses of dependencies and conflicts.\n bad_dep_timeout is the timeout to wait for a task to set finished status after its pid does not exist.\n Negative timeout means to ignore the timeout.\n \"\"\"\n start_time = time.time()\n bad_dep_start_times = {}\n run_task = False\n while True:\n self.try_lock_files()\n\n if self.locked:\n self.load_workers()\n\n dep_check = self.check_dependencies()\n if dep_check:\n # Dependencies satisfied, start running task\n run_task = True\n break\n\n if dep_check is not None:\n # Do not run task because of dependencies\n print('Failed dependency check')\n break\n\n # There are bad workers from the dependencies\n if bad_dep_timeout >= 0:\n for dep_id, worker_id in self.bad_dep_workers:\n if (dep_id, worker_id) in bad_dep_start_times:\n if time.time() - bad_dep_start_times[(dep_id, worker_id)] >= bad_dep_timeout:\n # timeout on waiting for the bad worker has been reached\n print('Bad dependency timeout reached, setting BAD_STATUS for', dep_id, worker_id)\n self.update_dep_worker(dep_id, [BAD_STATUS, str(worker_id)])\n del bad_dep_start_times[(dep_id, worker_id)]\n else:\n print('Waiting for status (pid does not exist) of', dep_id, worker_id)\n bad_dep_start_times[(dep_id, worker_id)] = time.time()\n\n self.unlock_files()\n time.sleep(delay)\n if timeout >= 0 and time.time() - start_time >= timeout:\n raise RuntimeError('Timeout exceeded')\n\n if run_task:\n print('Running', self.task_id)\n max_worker_id = -1\n for line in self.workers_lines:\n row = line.split()\n if row[0] == STARTED_STATUS:\n worker_id = int(row[1])\n if worker_id > max_worker_id:\n max_worker_id = worker_id\n\n worker_id = max_worker_id + 1\n proc = subprocess.Popen(self.command, shell=True, start_new_session=True)\n self.update_worker([STARTED_STATUS, str(worker_id), str(proc.pid)])\n else:\n print('Not running')\n\n self.unlock_files()\n\n if run_task:\n if SIMULATE_TASK_PROCESS_KILLED:\n print('killing', proc.pid)\n os.kill(proc.pid, signal.SIGKILL)\n\n if SIMULATE_TASK_RUNNER_KILLED:\n print('killing self', os.getpid())\n os.kill(os.getpid(), signal.SIGKILL)\n \n ret_val = proc.wait()\n\n if SIMULATE_SLOW_FINISH:\n print('Finishing slow')\n time.sleep(3)\n\n\n workers_lock = os.open(get_workers_lock(self.task_id), os.O_CREAT | os.O_RDONLY)\n fcntl.flock(workers_lock, fcntl.LOCK_EX)\n self.update_worker([FINISHED_STATUS, str(worker_id), str(ret_val)])\n fcntl.flock(workers_lock, fcntl.LOCK_UN)\n os.close(workers_lock)\n print('Finished')\n \n\n def try_lock_files(self):\n if self.workers_lock is not None or self.dep_workers_locks:\n raise RuntimeError('Locks already open')\n\n self.workers_lock = os.open(get_workers_lock(self.task_id), os.O_CREAT | os.O_RDONLY)\n if not flock_nb(self.workers_lock, fcntl.LOCK_EX):\n return\n\n dep_ids_set = set(self.dependency_ids)\n dep_ids_set.discard(self.task_id)\n for dep_id in dep_ids_set:\n dep_lock = os.open(get_workers_lock(dep_id), os.O_CREAT | os.O_RDONLY)\n self.dep_workers_locks[dep_id] = dep_lock\n if not flock_nb(dep_lock, fcntl.LOCK_EX):\n return\n\n self.locked = True\n\n def unlock_files(self):\n self.locked = False\n\n if self.workers_lock is not None:\n fcntl.flock(self.workers_lock, fcntl.LOCK_UN)\n os.close(self.workers_lock)\n self.workers_lines = None\n self.workers_lock = None\n\n for dep_lock in self.dep_workers_locks.values():\n fcntl.flock(dep_lock, fcntl.LOCK_UN)\n os.close(dep_lock)\n self.dep_workers_lines = None\n self.dep_workers_locks = {}\n self.bad_dep_workers = None\n\n def load_workers(self):\n if not self.locked:\n raise RuntimeError('Workers not locked')\n\n if os.path.isfile(get_workers_path(self.task_id)):\n with open(get_workers_path(self.task_id)) as f:\n self.workers_lines = f.readlines()\n else:\n self.workers_lines = []\n\n self.dep_workers_lines = {}\n dep_ids_set = set(self.dependency_ids)\n for dep_id in dep_ids_set:\n if os.path.isfile(get_workers_path(dep_id)):\n with open(get_workers_path(dep_id)) as f:\n self.dep_workers_lines[dep_id] = f.readlines()\n else:\n self.dep_workers_lines[dep_id] = []\n \n self.bad_dep_workers = []\n\n def update_worker(self, row):\n line = ' '.join(row) + '\\n'\n with open(get_workers_path(self.task_id), 'a') as f:\n f.write(line)\n\n def update_dep_worker(self, dep_id, row):\n line = ' '.join(row) + '\\n'\n with open(get_workers_path(dep_id), 'a') as f:\n f.write(line)\n\n def check_dependencies(self):\n \"\"\"\n dependencies must have no workers running and the last task\n must have finished successfully\n \"\"\"\n\n dependency_check = True\n\n for dep_id in self.dependency_ids:\n if not self.dep_workers_lines[dep_id]:\n # No workers for the dependency have started yet\n dependency_check = False\n continue\n\n unfinished_workers = {}\n\n for line in self.dep_workers_lines[dep_id]:\n rows = line.split()\n if rows[0] == STARTED_STATUS:\n worker_id = int(rows[1])\n pid = int(rows[2])\n if worker_id in unfinished_workers:\n raise RuntimeError('Invalid worker state')\n unfinished_workers[worker_id] = pid\n elif rows[0] == FINISHED_STATUS:\n worker_id = int(rows[1])\n ret_val = int(rows[2])\n del unfinished_workers[worker_id]\n elif rows[0] == BAD_STATUS:\n worker_id = int(rows[1])\n del unfinished_workers[worker_id]\n else:\n raise RuntimeError('Invalid status')\n\n if unfinished_workers:\n for worker_id, pid in unfinished_workers.items():\n if self.check_bad_pid(dep_id, worker_id, pid):\n if dependency_check:\n dependency_check = None\n else:\n dependency_check = False\n\n else:\n # check that the last worker finished with a 0 status\n last_worker_rows = self.dep_workers_lines[dep_id][-1].split()\n if last_worker_rows[0] != FINISHED_STATUS or last_worker_rows[2] != '0':\n print('Last status not finished 0 for', dep_id)\n dependency_check = False\n else:\n # check there are no bad statuses from when the worker started\n for line in reversed(self.dep_workers_lines[dep_id][:-1]):\n rows = line.split()\n if rows[0] == STARTED_STATUS:\n if rows[1] == last_worker_rows[1]:\n break\n elif rows[0] == FINISHED_STATUS:\n if rows[2] != '0':\n dependency_check = False\n elif rows[0] == BAD_STATUS:\n dependency_check = False\n else:\n raise RuntimeError('Unstarted worker')\n\n return dependency_check\n\n def check_bad_pid(self, dep_id, worker_id, pid):\n # Worker had started, but if the task was killed, then\n # the status would not have updated\n # Check if the pid exists, not a great solution according to\n # http://mywiki.wooledge.org/ProcessManagement#The_risk_of_letting_the_parent_die\n # but the safer alternative is not viable because we are assuming\n # that the parent process runner can be killed\n if pid_exists(pid):\n return False\n\n # Assume that the task had finished, mark it as bad\n self.bad_dep_workers.append((dep_id, worker_id))\n\n return True\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('task_id')\n parser.add_argument('--kill-runner', action='store_true')\n parser.add_argument('--kill-process', action='store_true')\n parser.add_argument('--slow-finish', action='store_true')\n args = parser.parse_args()\n\n global SIMULATE_TASK_RUNNER_KILLED\n SIMULATE_TASK_RUNNER_KILLED = args.kill_runner\n global SIMULATE_TASK_PROCESS_KILLED\n SIMULATE_TASK_PROCESS_KILLED = args.kill_process\n global SIMULATE_SLOW_FINISH\n SIMULATE_SLOW_FINISH = args.slow_finish\n\n task_id = args.task_id\n\n with open(CONFIG_FILE) as f:\n config = json.load(f)\n\n task = None\n\n for config_task in config:\n if config_task['id'] == task_id:\n task = config_task\n break\n\n if task is None:\n raise RuntimeError('Task id not configured')\n\n for config_task in config:\n make_dir_exist(get_task_dir(config_task['id']))\n\n runner = TaskRunner(task['id'], task['command'], task['dependencies'])\n runner.run()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"task_runner.py","file_name":"task_runner.py","file_ext":"py","file_size_in_byte":12142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"78319436","text":"'''Implementation of counting sort'''\ndef countingsort(unsorted_numbers, max):\n numbers_to_count = [0]*(max+1)\n for number in unsorted_numbers:\n numbers_to_count[number] += 1\n sorted_numbers = []\n for number, count in enumerate(numbers_to_count):\n for number_of_times in range(count):\n sorted_numbers.append(number)\n return sorted_numbers\nprint(countingsort([4,6,2,2,7,3,8,9],9))\nprint(countingsort([4,6,2,7,3,8,9],9))\n","sub_path":"Searching&Sorting/CountingSort.py","file_name":"CountingSort.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"550154132","text":"import random\r\nimport time\r\n\r\ndef quitGame():\r\n print(\"3\")\r\n time.sleep(1)\r\n print(\"2\")\r\n time.sleep(1)\r\n print(\"1\")\r\n time.sleep(1)\r\n print(\"bye bye\")\r\n exit()\r\n\r\ndef playGame():\r\n\r\n winner = False\r\n loser = False\r\n\r\n while winner == loser:\r\n roundOne = 0\r\n roundTwo = 0\r\n roundThree = 0\r\n\r\n options = [\"rock\", \"paper\", \"scissors\"]\r\n numOptions = [1, 2, 3]\r\n\r\n while roundOne == 0:\r\n print(\"Round One!!\")\r\n print(\"In a moment, you will choose either rock, paper, or scissors with **A NUMBER**\")\r\n time.sleep(1)\r\n playerChoice = input(\"Please choose rock[1], paper[2], scissors[3]: \")\r\n try:\r\n playerChoice = int(playerChoice)\r\n if playerChoice in numOptions:\r\n playerChoice = options[(playerChoice - 1)]\r\n except:\r\n print(\"You must have put in a bad input. Let's try this round again!\")\r\n\r\n opponentChoice = options[random.randint(0, 2)]\r\n\r\n if playerChoice == opponentChoice:\r\n print(f\"You both had {playerChoice}!\")\r\n print(\"Let's try this round again!\")\r\n roundOne = 0\r\n else:\r\n print(f\"You chose {playerChoice}, and your opponent chose {opponentChoice}.\")\r\n if (playerChoice == \"rock\") and (opponentChoice == \"scissors\"):\r\n print(\"win\")\r\n roundOne = 1\r\n elif (playerChoice == \"scissors\") and (opponentChoice == \"paper\"):\r\n print(\"win\")\r\n roundOne = 1\r\n elif (playerChoice == \"paper\") and (opponentChoice == \"rock\"):\r\n print(\"win\")\r\n roundOne = 1\r\n else:\r\n print(\"lose\")\r\n roundOne = 2\r\n\r\n\r\n while roundTwo == 0:\r\n print(\"Round Two!!\")\r\n print(\"In a moment, you will choose either rock, paper, or scissors with **A NUMBER**\")\r\n time.sleep(1)\r\n playerChoice = input(\"Please choose rock[1], paper[2], scissors[3]: \")\r\n try:\r\n playerChoice = int(playerChoice)\r\n if playerChoice in numOptions:\r\n playerChoice = options[(playerChoice - 1)]\r\n except:\r\n print(\"You must have put in a bad input. Let's try this round again!\")\r\n\r\n opponentChoice = options[random.randint(0, 2)]\r\n\r\n if playerChoice == opponentChoice:\r\n print(f\"You both had {playerChoice}!\")\r\n print(\"Let's try this round again!\")\r\n roundTwo = 0\r\n else:\r\n print(f\"You chose {playerChoice}, and your opponent chose {opponentChoice}.\")\r\n if (playerChoice == \"rock\") and (opponentChoice == \"scissors\"):\r\n print(\"win\")\r\n roundTwo = 1\r\n elif (playerChoice == \"scissors\") and (opponentChoice == \"paper\"):\r\n print(\"win\")\r\n roundTwo = 1\r\n elif (playerChoice == \"paper\") and (opponentChoice == \"rock\"):\r\n print(\"win\")\r\n roundTwo = 1\r\n else:\r\n print(\"lose\")\r\n roundTwo = 2\r\n\r\n if roundOne == roundTwo:\r\n roundThree = roundOne\r\n\r\n while roundThree == 0:\r\n print(\"Round Three!!\")\r\n print(\"In a moment, you will choose either rock, paper, or scissors with **A NUMBER**\")\r\n time.sleep(1)\r\n playerChoice = input(\"Please choose rock[1], paper[2], scissors[3]: \")\r\n try:\r\n playerChoice = int(playerChoice)\r\n if playerChoice in numOptions:\r\n playerChoice = options[(playerChoice - 1)]\r\n except:\r\n print(\"You must have put in a bad input. Let's try this round again!\")\r\n\r\n opponentChoice = options[random.randint(0, 2)]\r\n\r\n if playerChoice == opponentChoice:\r\n print(f\"You both had {playerChoice}!\")\r\n print(\"Let's try this round again!\")\r\n roundThree = 0\r\n else:\r\n print(f\"You chose {playerChoice}, and your opponent chose {opponentChoice}.\")\r\n if (playerChoice == \"rock\") and (opponentChoice == \"scissors\"):\r\n print(\"win\")\r\n roundThree = 1\r\n elif (playerChoice == \"scissors\") and (opponentChoice == \"paper\"):\r\n print(\"win\")\r\n roundThree = 1\r\n elif (playerChoice == \"paper\") and (opponentChoice == \"rock\"):\r\n print(\"win\")\r\n roundThree = 1\r\n else:\r\n print(\"lose\")\r\n roundThree = 2\r\n\r\n if (roundOne == 1 and roundTwo == 1) or (roundOne == 1 and roundThree == 1) or (roundTwo == 1 and roundThree == 1):\r\n winner = True\r\n print(\"You're the winner!\")\r\n time.sleep(1)\r\n elif (roundOne == 2 and roundTwo == 2) or (roundOne == 2 and roundThree == 2) or (roundTwo == 2 and roundThree == 2):\r\n loser = True\r\n print(\"Sorry, you lost.\")\r\n\r\n\r\n print(\"\")\r\n startGame = False\r\n\r\nprint(\"Let's play rock, paper, scissors!\")\r\ntime.sleep(.5)\r\n\r\nstartGame = False\r\n\r\nrpsrules = \"\"\r\nwhile rpsrules == \"\":\r\n rpsrules = input(\"Do you know how to play (yes/no): \")\r\n if rpsrules.lower() == \"yes\":\r\n wannaPlay = input(\"Would you like to play (yes/no): \")\r\n if wannaPlay.lower() == \"yes\":\r\n startGame = True\r\n elif wannaPlay.lower() == \"no\":\r\n print(\"Okay...\")\r\n quitGame()\r\n else:\r\n print(\"seems you mistyped...\")\r\n print(\"Let the games begin, anyway!\")\r\n startGame = True\r\n elif rpsrules.lower() == \"no\":\r\n print(\"In rock, paper, scissors you and your opponent want to win each round.\")\r\n time.sleep(2.5)\r\n print(\"Each round you will choose one of three choices: rock, paper, or scissors.\")\r\n time.sleep(2.5)\r\n print(\"In rock, paper, scissors: rock > scissors; paper > rock; scissors > paper.\")\r\n time.sleep(2.5)\r\n print(\"Your goal is to win at least 2 of 3 rounds.\")\r\n time.sleep(5)\r\n print(\"Let's begin!\")\r\n startGame = True\r\n time.sleep(.5)\r\n else:\r\n print(\"You mistyped.\")\r\n rpsrules = \"\"\r\n\r\nwhile startGame:\r\n playGame()\r\n startGame = False\r\n\r\nprint(\"Thanks for playing!\")\r\n","sub_path":"rockPaperScizzors.py","file_name":"rockPaperScizzors.py","file_ext":"py","file_size_in_byte":6688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"540317646","text":"import json\nimport os\nimport tempfile\nimport numpy as np\nimport numba\nfrom enum import IntEnum\n\nimport strax\nimport straxen\nfrom straxen.common import pax_file, get_resource, first_sr1_run\nexport, __all__ = strax.exporter()\nfrom .pulse_processing import HE_PREAMBLE\n\n\n@export\n@strax.takes_config(\n strax.Option('n_top_pmts', default=straxen.n_top_pmts, infer_type=False,\n help=\"Number of top PMTs\"),\n strax.Option('check_peak_sum_area_rtol', default=None, track=False, infer_type=False,\n help=\"Check if the sum area and the sum of area per \"\n \"channel are the same. If None, don't do the \"\n \"check. To perform the check, set to the desired \"\n \" rtol value used e.g. '1e-4' (see np.isclose).\"),\n)\nclass PeakBasics(strax.Plugin):\n \"\"\"\n Compute the basic peak-properties, thereby dropping structured\n arrays.\n NB: This plugin can therefore be loaded as a pandas DataFrame.\n \"\"\"\n __version__ = \"0.1.0\"\n parallel = True\n depends_on = ('peaks',)\n provides = 'peak_basics'\n dtype = [\n (('Start time of the peak (ns since unix epoch)',\n 'time'), np.int64),\n (('End time of the peak (ns since unix epoch)',\n 'endtime'), np.int64),\n (('Weighted center time of the peak (ns since unix epoch)',\n 'center_time'), np.int64),\n (('Peak integral in PE',\n 'area'), np.float32),\n (('Number of PMTs contributing to the peak',\n 'n_channels'), np.int16),\n (('PMT number which contributes the most PE',\n 'max_pmt'), np.int16),\n (('Area of signal in the largest-contributing PMT (PE)',\n 'max_pmt_area'), np.float32),\n (('Total number of saturated channels',\n 'n_saturated_channels'), np.int16),\n (('Width (in ns) of the central 50% area of the peak',\n 'range_50p_area'), np.float32),\n (('Width (in ns) of the central 90% area of the peak',\n 'range_90p_area'), np.float32),\n (('Fraction of area seen by the top array '\n '(NaN for peaks with non-positive area)',\n 'area_fraction_top'), np.float32),\n (('Length of the peak waveform in samples',\n 'length'), np.int32),\n (('Time resolution of the peak waveform in ns',\n 'dt'), np.int16),\n (('Time between 10% and 50% area quantiles [ns]',\n 'rise_time'), np.float32),\n (('Hits within tight range of mean',\n 'tight_coincidence'), np.int16),\n (('PMT channel within tight range of mean',\n 'tight_coincidence_channel'), np.int16),\n (('Classification of the peak(let)',\n 'type'), np.int8)\n ]\n\n def compute(self, peaks):\n p = peaks\n r = np.zeros(len(p), self.dtype)\n for q in 'time length dt area type'.split():\n r[q] = p[q]\n r['endtime'] = p['time'] + p['dt'] * p['length']\n r['n_channels'] = (p['area_per_channel'] > 0).sum(axis=1)\n r['range_50p_area'] = p['width'][:, 5]\n r['range_90p_area'] = p['width'][:, 9]\n r['max_pmt'] = np.argmax(p['area_per_channel'], axis=1)\n r['max_pmt_area'] = np.max(p['area_per_channel'], axis=1)\n r['tight_coincidence'] = p['tight_coincidence']\n r['n_saturated_channels'] = p['n_saturated_channels']\n\n n_top = self.config['n_top_pmts']\n area_top = p['area_per_channel'][:, :n_top].sum(axis=1)\n # Recalculate to prevent numerical inaccuracy #442\n area_total = p['area_per_channel'].sum(axis=1)\n # Negative-area peaks get NaN AFT\n m = p['area'] > 0\n r['area_fraction_top'][m] = area_top[m]/area_total[m]\n r['area_fraction_top'][~m] = float('nan')\n r['rise_time'] = -p['area_decile_from_midpoint'][:, 1]\n\n if self.config['check_peak_sum_area_rtol'] is not None:\n self.check_area(area_total, p, self.config['check_peak_sum_area_rtol'])\n # Negative or zero-area peaks have centertime at startime\n r['center_time'] = p['time']\n r['center_time'][m] += self.compute_center_times(peaks[m])\n return r\n\n @staticmethod\n @numba.njit(cache=True, nogil=True)\n def compute_center_times(peaks):\n result = np.zeros(len(peaks), dtype=np.int32)\n for p_i, p in enumerate(peaks):\n t = 0\n for t_i, weight in enumerate(p['data']):\n t += t_i * p['dt'] * weight\n result[p_i] = t / p['area']\n return result\n\n @staticmethod\n def check_area(area_per_channel_sum, peaks, rtol) -> None:\n \"\"\"\n Check if the area of the sum-wf is the same as the total area\n (if the area of the peak is positively defined).\n\n :param area_per_channel_sum: the summation of the\n peaks['area_per_channel'] which will be checked against the\n values of peaks['area'].\n :param peaks: array of peaks.\n :param rtol: relative tolerance for difference between\n area_per_channel_sum and peaks['area']. See np.isclose.\n :raises: ValueError if the peak area and the area-per-channel\n sum are not sufficiently close\n \"\"\"\n positive_area = peaks['area'] > 0\n if not np.sum(positive_area):\n return\n\n is_close = np.isclose(area_per_channel_sum[positive_area],\n peaks[positive_area]['area'],\n rtol=rtol,\n )\n\n if not is_close.all():\n for peak in peaks[positive_area][~is_close]:\n print('bad area')\n strax.print_record(peak)\n\n p_i = np.where(~is_close)[0][0]\n peak = peaks[positive_area][p_i]\n area_fraction_off = 1 - area_per_channel_sum[positive_area][p_i] / peak['area']\n message = (f'Area not calculated correctly, it\\'s '\n f'{100*area_fraction_off} % off, time: {peak[\"time\"]}')\n raise ValueError(message)\n\n\n@export\nclass PeakBasicsHighEnergy(PeakBasics):\n __doc__ = HE_PREAMBLE + PeakBasics.__doc__\n __version__ = '0.0.2'\n depends_on = 'peaks_he'\n provides = 'peak_basics_he'\n child_ends_with = '_he'\n\n def compute(self, peaks_he):\n return super().compute(peaks_he)\n\n\n@export\n@strax.takes_config(\n strax.Option(\n 'nn_architecture', infer_type=False,\n help='Path to JSON of neural net architecture',\n default_by_run=[\n (0, pax_file('XENON1T_tensorflow_nn_pos_20171217_sr0.json')),\n (first_sr1_run, straxen.aux_repo + '3548132b55f81a43654dba5141366041e1daaf01/strax_files/XENON1T_tensorflow_nn_pos_20171217_sr1_reformatted.json')]), # noqa\n strax.Option(\n 'nn_weights', infer_type=False,\n help='Path to HDF5 of neural net weights',\n default_by_run=[\n (0, pax_file('XENON1T_tensorflow_nn_pos_weights_20171217_sr0.h5')),\n (first_sr1_run, pax_file('XENON1T_tensorflow_nn_pos_weights_20171217_sr1.h5'))]), # noqa\n strax.Option('min_reconstruction_area',\n help='Skip reconstruction if area (PE) is less than this',\n default=10, infer_type=False,),\n strax.Option('n_top_pmts', default=straxen.n_top_pmts, infer_type=False,\n help=\"Number of top PMTs\")\n)\nclass PeakPositions1T(strax.Plugin):\n \"\"\"Compute the S2 (x,y)-position based on a neural net.\"\"\"\n dtype = [('x', np.float32,\n 'Reconstructed S2 X position (cm), uncorrected'),\n ('y', np.float32,\n 'Reconstructed S2 Y position (cm), uncorrected')\n ] + strax.time_fields\n depends_on = ('peaks',)\n provides = \"peak_positions\"\n\n # Parallelization doesn't seem to make it go faster\n # Is there much pure-python stuff in tensorflow?\n # Process-level paralellization might work, but you'd have to do setup\n # in each process, which probably negates the benefits,\n # except for huge chunks\n parallel = False\n\n __version__ = '0.1.1'\n\n def setup(self):\n import tensorflow as tf\n keras = tf.keras\n nn_conf = get_resource(self.config['nn_architecture'], fmt='json')\n # badPMTList was inserted by a very clever person into the keras json\n # file. Let's delete it to prevent future keras versions from crashing.\n # Do NOT try `del nn_conf['badPMTList']`! See get_resource docstring\n # for the gruesome details.\n bad_pmts = nn_conf['badPMTList']\n nn = keras.models.model_from_json(json.dumps({\n k: v\n for k, v in nn_conf.items()\n if k != 'badPMTList'}))\n self.pmt_mask = ~np.in1d(np.arange(self.config['n_top_pmts']),\n bad_pmts)\n\n # Keras needs a file to load its weights. We can't put the load\n # inside the context, then it would break on Windows,\n # because there temporary files cannot be opened again.\n with tempfile.NamedTemporaryFile(delete=False) as f:\n f.write(get_resource(self.config['nn_weights'],\n fmt='binary'))\n fname = f.name\n nn.load_weights(fname)\n os.remove(fname)\n self.nn = nn\n\n def compute(self, peaks):\n result = np.ones(len(peaks), dtype=self.dtype)\n result['time'], result['endtime'] = peaks['time'], strax.endtime(peaks)\n result['x'] *= float('nan')\n result['y'] *= float('nan')\n\n # Keep large peaks only\n peak_mask = peaks['area'] > self.config['min_reconstruction_area']\n if not np.sum(peak_mask):\n # Nothing to do, and .predict crashes on empty arrays\n return result\n\n # Input: normalized hitpatterns in good top PMTs\n _in = peaks['area_per_channel'][peak_mask, :]\n _in = _in[:, :self.config['n_top_pmts']][:, self.pmt_mask]\n with np.errstate(divide='ignore', invalid='ignore'):\n _in /= _in.sum(axis=1).reshape(-1, 1)\n\n # Output: positions in mm (unfortunately), so convert to cm\n _out = self.nn.predict(_in) / 10\n\n # Set output in valid rows. Do NOT try result[peak_mask]['x']\n # unless you want all NaN positions (boolean masks make a copy unless\n # they are used as the last index)\n result['x'][peak_mask] = _out[:, 0]\n result['y'][peak_mask] = _out[:, 1]\n return result\n\n\n@export\n@strax.takes_config(\n strax.Option('min_area_fraction', default=0.5, infer_type=False,\n help='The area of competing peaks must be at least '\n 'this fraction of that of the considered peak'),\n strax.Option('nearby_window', default=int(1e7), infer_type=False,\n help='Peaks starting within this time window (on either side)'\n 'in ns count as nearby.'),\n strax.Option('peak_max_proximity_time', default=int(1e8), infer_type=False,\n help='Maximum value for proximity values such as '\n 't_to_next_peak [ns]'))\nclass PeakProximity(strax.OverlapWindowPlugin):\n \"\"\"\n Look for peaks around a peak to determine how many peaks are in\n proximity (in time) of a peak.\n \"\"\"\n depends_on = ('peak_basics',)\n dtype = [\n ('n_competing', np.int32,\n 'Number of nearby larger or slightly smaller peaks'),\n ('n_competing_left', np.int32,\n 'Number of larger or slightly smaller peaks left of the main peak'),\n ('t_to_prev_peak', np.int64,\n 'Time between end of previous peak and start of this peak [ns]'),\n ('t_to_next_peak', np.int64,\n 'Time between end of this peak and start of next peak [ns]'),\n ('t_to_nearest_peak', np.int64,\n 'Smaller of t_to_prev_peak and t_to_next_peak [ns]')\n ] + strax.time_fields\n\n __version__ = '0.4.0'\n\n def get_window_size(self):\n return self.config['peak_max_proximity_time']\n\n def compute(self, peaks):\n windows = strax.touching_windows(peaks, peaks,\n window=self.config['nearby_window'])\n n_left, n_tot = self.find_n_competing(\n peaks,\n windows,\n fraction=self.config['min_area_fraction'])\n\n t_to_prev_peak = (\n np.ones(len(peaks), dtype=np.int64)\n * self.config['peak_max_proximity_time'])\n t_to_prev_peak[1:] = peaks['time'][1:] - peaks['endtime'][:-1]\n\n t_to_next_peak = t_to_prev_peak.copy()\n t_to_next_peak[:-1] = peaks['time'][1:] - peaks['endtime'][:-1]\n\n return dict(\n time=peaks['time'],\n endtime=strax.endtime(peaks),\n n_competing=n_tot,\n n_competing_left=n_left,\n t_to_prev_peak=t_to_prev_peak,\n t_to_next_peak=t_to_next_peak,\n t_to_nearest_peak=np.minimum(t_to_prev_peak, t_to_next_peak))\n\n @staticmethod\n @numba.jit(nopython=True, nogil=True, cache=True)\n def find_n_competing(peaks, windows, fraction):\n n_left = np.zeros(len(peaks), dtype=np.int32)\n n_tot = n_left.copy()\n areas = peaks['area']\n\n for i, peak in enumerate(peaks):\n left_i, right_i = windows[i]\n threshold = areas[i] * fraction\n n_left[i] = np.sum(areas[left_i:i] > threshold)\n n_tot[i] = n_left[i] + np.sum(areas[i + 1:right_i] > threshold)\n\n return n_left, n_tot\n\n@export\n@strax.takes_config(\n strax.Option(name='pre_s2_area_threshold', default=1000,\n help='Only take S2s larger than this into account '\n 'when calculating PeakShadow [PE]'),\n strax.Option(name='deltatime_exponent', default=-1.0,\n help='The exponent of delta t when calculating shadow'),\n strax.Option('time_window_backward', default=int(3e9),\n help='Search for S2s causing shadow in this time window [ns]'),\n strax.Option(name='electron_drift_velocity',\n default=('electron_drift_velocity', 'ONLINE', True),\n help='Vertical electron drift velocity in cm/ns (1e4 m/ms)'),\n strax.Option(name='max_drift_length', default=straxen.tpc_z,\n help='Total length of the TPC from the bottom of gate to the '\n 'top of cathode wires [cm]'),\n strax.Option(name='exclude_drift_time', default=False,\n help='Subtract max drift time to avoid peak interference in '\n 'a single event [ns]'))\nclass PeakShadow(strax.OverlapWindowPlugin):\n \"\"\"\n This plugin can find and calculate the previous S2 shadow at peak level,\n with time window backward and previous S2 area as options.\n It also gives the area and position information of these previous S2s.\n \"\"\"\n\n __version__ = '0.1.0'\n depends_on = ('peak_basics', 'peak_positions')\n provides = 'peak_shadow'\n save_when = strax.SaveWhen.EXPLICIT\n\n def setup(self):\n self.time_window_backward = self.config['time_window_backward']\n if self.config['exclude_drift_time']:\n electron_drift_velocity = straxen.get_correction_from_cmt(\n self.run_id,\n self.config['electron_drift_velocity'])\n drift_time_max = int(self.config['max_drift_length'] / electron_drift_velocity)\n self.n_drift_time = drift_time_max\n else:\n self.n_drift_time = 0\n self.s2_threshold = self.config['pre_s2_area_threshold']\n self.exponent = self.config['deltatime_exponent']\n\n def get_window_size(self):\n return 3 * self.config['time_window_backward']\n\n def infer_dtype(self):\n dtype = [('shadow', np.float32, 'previous s2 shadow [PE/ns]'),\n ('pre_s2_area', np.float32, 'previous s2 area [PE]'),\n ('shadow_dt', np.int64, 'time difference to the previous s2 [ns]'),\n ('pre_s2_x', np.float32, 'x of previous s2 peak causing shadow [cm]'),\n ('pre_s2_y', np.float32, 'y of previous s2 peak causing shadow [cm]')]\n dtype += strax.time_fields\n return dtype\n\n def compute(self, peaks):\n roi_shadow = np.zeros(len(peaks), dtype=strax.time_fields)\n roi_shadow['time'] = peaks['center_time'] - self.time_window_backward\n roi_shadow['endtime'] = peaks['center_time'] - self.n_drift_time\n\n mask_pre_s2 = peaks['area'] > self.s2_threshold\n mask_pre_s2 &= peaks['type'] == 2\n split_peaks = strax.touching_windows(peaks[mask_pre_s2], roi_shadow)\n res = np.zeros(len(peaks), self.dtype)\n res['pre_s2_x'] = np.nan\n res['pre_s2_y'] = np.nan\n if len(peaks):\n self.compute_shadow(peaks, peaks[mask_pre_s2], split_peaks, self.exponent, res)\n\n res['time'] = peaks['time']\n res['endtime'] = strax.endtime(peaks)\n return res\n\n @staticmethod\n @numba.njit\n def compute_shadow(peaks, pre_s2_peaks, touching_windows, exponent, res):\n \"\"\"\n For each peak in peaks, check if there is a shadow-casting S2 peak\n and check if it casts the largest shadow\n \"\"\"\n for p_i, p_a in enumerate(peaks):\n # reset for every peak\n new_shadow = 0\n s2_indices = touching_windows[p_i]\n for s2_idx in range(s2_indices[0], s2_indices[1]):\n s2_a = pre_s2_peaks[s2_idx]\n if p_a['center_time'] - s2_a['center_time'] <= 0:\n continue\n new_shadow = s2_a['area'] * (\n p_a['center_time'] - s2_a['center_time'])**exponent\n if new_shadow > res['shadow'][p_i]:\n res['shadow'][p_i] = new_shadow\n res['pre_s2_area'][p_i] = s2_a['area']\n res['shadow_dt'][p_i] = p_a['center_time'] - s2_a['center_time']\n res['pre_s2_x'][p_i] = s2_a['x']\n res['pre_s2_y'][p_i] = s2_a['y']\n\n\n@export\nclass VetoPeakTags(IntEnum):\n \"\"\"Identifies by which detector peak was tagged.\n \"\"\"\n # Peaks are not inside any veto interval\n NO_VETO = 0\n # Peaks are inside a veto interval issued by:\n NEUTRON_VETO = 1\n MUON_VETO = 2\n BOTH = 3\n\n\n@export\nclass PeakVetoTagging(strax.Plugin):\n \"\"\"\n Plugin which tags S1 peaks according to muon and neutron-vetos.\n Tagging S2s is does not make sense as they occur with a delay.\n However, we compute for both S1/S2 the time delay to the closest veto\n region.\n\n * untagged: 0\n * neutron-veto: 1\n * muon-veto: 2\n * both vetos: 3\n \"\"\"\n __version__ = '0.0.1'\n depends_on = ('peak_basics', 'veto_regions_nv', 'veto_regions_mv')\n provides = ('peak_veto_tags')\n save_when = strax.SaveWhen.TARGET\n\n dtype = strax.time_fields + [\n ('veto_tag', np.int8,\n 'Veto tag for S1 peaks. unatagged: 0, nveto: 1, mveto: 2, both: 3'),\n ('time_to_closest_veto', np.int64, 'Time to closest veto interval boundary in ns (can be '\n 'negative if closest boundary comes before peak.). ')\n ]\n\n def get_time_difference(self, peaks, veto_regions_nv, veto_regions_mv):\n \"\"\"\n Computes time differences to closest nv/mv veto signal.\n\n It might be that neutron-veto and muon-veto signals overlap\n Hence we compute first the individual time differences to the\n corresponding vetos and keep afterwards the smallest ones.\n \"\"\"\n dt_nv = get_time_to_closest_veto(peaks, veto_regions_nv)\n dt_mv = get_time_to_closest_veto(peaks, veto_regions_mv)\n\n dts = np.transpose([dt_nv, dt_mv])\n ind_axis1 = np.argmin(np.abs(dts), axis=1)\n return self._get_smallest_value(dts, ind_axis1)\n\n @staticmethod\n @numba.njit(cache=True, nogil=True)\n def _get_smallest_value(time_differences, index):\n res = np.zeros(len(time_differences), np.int64)\n for res_ind, (ind, dt) in enumerate(zip(index, time_differences)):\n res[res_ind] = dt[ind]\n return res\n\n def compute(self, peaks, veto_regions_nv, veto_regions_mv):\n touching_mv = strax.touching_windows(peaks, veto_regions_mv)\n touching_nv = strax.touching_windows(peaks, veto_regions_nv)\n\n tags = np.zeros(len(peaks))\n tags = tag_peaks(tags, touching_nv, straxen.VetoPeakTags.NEUTRON_VETO)\n tags = tag_peaks(tags, touching_mv, straxen.VetoPeakTags.MUON_VETO)\n\n dt = self.get_time_difference(peaks, veto_regions_nv, veto_regions_mv)\n return {'time': peaks['time'],\n 'endtime': strax.endtime(peaks),\n 'veto_tag': tags,\n 'time_to_closest_veto': dt,\n }\n\n\n@numba.njit(cache=True, nogil=True)\ndef tag_peaks(tags, touching_windows, tag_number):\n \"\"\"Tags every peak which are within the corresponding touching window\n with the defined tag number.\n\n :param tags: numpy.array in which the tags should be stored. Should\n be of length peaks.\n :param touching_windows: Start/End index of tags to be set to tag\n value.\n :param tag_number: integer representing the tag.\n :return: Updated tags.\n \"\"\"\n pre_tags = np.zeros(len(tags), dtype=np.int8)\n for start, end in touching_windows:\n pre_tags[start:end] = tag_number\n tags += pre_tags\n return tags\n\n\ndef get_time_to_closest_veto(peaks, veto_intervals):\n \"\"\"Computes time difference between peak and closest veto interval.\n\n The time difference is always computed from peaks-time field to\n the time or endtime of the veto_interval depending on which distance\n is smaller.\n \"\"\"\n vetos = np.zeros(len(veto_intervals)+2, strax.time_fields)\n vetos[1:-1]['time'] = veto_intervals['time']\n vetos[1:-1]['endtime'] = strax.endtime(veto_intervals)\n vetos[-1]['time'] = straxen.INFINITY_64BIT_SIGNED\n vetos[-1]['endtime'] = straxen.INFINITY_64BIT_SIGNED\n vetos[0]['time'] = -straxen.INFINITY_64BIT_SIGNED\n vetos[0]['endtime'] = -straxen.INFINITY_64BIT_SIGNED\n return _get_time_to_closest_veto(peaks, vetos)\n\n\n@numba.njit(cache=True, nogil=True)\ndef _get_time_to_closest_veto(peaks, vetos):\n res = np.zeros(len(peaks), dtype=np.int64)\n veto_index = 0\n for ind, p in enumerate(peaks):\n for veto_index in range(veto_index, len(vetos)):\n if veto_index+1 == len(vetos):\n # If we reach here all future peaks are closest to last veto:\n res[ind] = np.abs(vetos[-1]['time'] - p['time'])\n break\n\n # Current interval can be before or after current peak, hence\n # we have to check which distance is smaller.\n dt_current_veto = min(np.abs(vetos[veto_index]['time'] - p['time']),\n np.abs(vetos[veto_index]['endtime'] - p['time'])\n )\n # Next interval is always further in the future as the\n # current one, hence we only have to compute distance with \"time\".\n dt_next_veto = np.abs(vetos[veto_index+1]['time'] - p['time'])\n\n # Next veto is closer so we have to repeat in case next + 1\n # is even closer.\n if dt_current_veto >= dt_next_veto:\n veto_index += 1\n continue\n\n # Now compute time difference for real:\n dt_time = vetos[veto_index]['time'] - p['time']\n dt_endtime = vetos[veto_index]['endtime'] - p['time']\n\n if np.abs(dt_time) < np.abs(dt_endtime):\n res[ind] = dt_time\n else:\n res[ind] = dt_endtime\n break\n\n return res\n","sub_path":"straxen/plugins/peak_processing.py","file_name":"peak_processing.py","file_ext":"py","file_size_in_byte":23690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290822987","text":"import itertools\nimport logging\nimport math\nimport numpy as np\nimport pandas as pd \n\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport scipy.stats as stats\nimport seaborn as sns\nimport warnings\n\nfrom pandas.plotting import scatter_matrix\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.impute import SimpleImputer\n\nimport pdb\nimport warnings\n\nwarnings.filterwarnings('ignore')\nlogging.basicConfig(level=logging.WARNING)\nlog = logging.getLogger(__name__)\nstyle.use('bmh') ## style for charts\n\n\nclass autoEDA:\n\n def __init__(self, df, eda_type, target=None, max_categories=None):\n DEFAULT_MAX_CATEGORIES = 20\n max_categories = max_categories if max_categories is not None else DEFAULT_MAX_CATEGORIES\n\n self._validate_input_df(df)\n self._validate_input_target(df, target)\n self._validate_input_params(max_categories)\n\n numeric_cols, categorical_cols, combined_cols, all_cols = self._col_types(df, target)\n df = df[all_cols] #remove any non-numeric, non-categorical fields (ie dates)\n df = self._format_df_target(df, target)\n df = self._df_bin_max_categories(df, categorical_cols, max_categories)\n \n self.df = df\n self.target = target\n self.eda_type = eda_type\n self.numeric_cols = numeric_cols\n self.categorical_cols = categorical_cols\n self.combined_cols = combined_cols\n self.all_cols = all_cols\n self.max_categories = max_categories \n self._ranked_numeric_cols = self._rank_numeric_cols(df, target, numeric_cols)\n self._ranked_categorical_cols = self._rank_categorical_cols(df, target, categorical_cols)\n self._bar_lineplot_reference = None\n\n def _validate_input_df(self, df):\n \"\"\" Validate the input of class instantiation \"\"\"\n if not isinstance(df, pd.DataFrame): \n raise ValueError('Invalid input, please input a pandas DataFrame')\n if df.shape[1] < 2: raise ValueError('Dataframe must have at least 2 columns')\n if df.shape[0] < 10: raise ValueError('Dataframe must have at least 10 rows') \n\n def _validate_input_target(self, df, target):\n raise NotImplementedError\n\n # for binary classification:\n #if not isinstance(target, str): raise ValueError('Invalid target: {t}'.format(t=target))\n #if target not in df.columns: raise ValueError('Target not in dataframe: {t}'.format(t=target))\n\n def _validate_input_params(self, max_categories):\n if max_categories and not isinstance(max_categories, int): \n raise ValueError('Invalid max_categories parameter, must be int')\n if max_categories and max_categories < 2: raise ValueError('Max categories must be greater than 1')\n\n def _col_types(self, df, target):\n df_na_filled = df.fillna(value=0)\n numeric_cols = set(df_na_filled.select_dtypes(include=np.number).columns)\n categorical_cols_overlap = set(df.select_dtypes(include=['object','bool','category']).columns)\n categorical_cols = categorical_cols_overlap - numeric_cols\n\n numeric_cols.discard(target)\n categorical_cols.discard(target)\n\n combined_cols = numeric_cols.union(categorical_cols)\n all_cols = combined_cols.union([target]) if target is not None else combined_cols\n unusable_cols = list(set(df.columns) - set(all_cols))\n if len(unusable_cols) > 0:\n log.warning('Unable to use the following colunms: {uc}'.format(uc=unusable_cols))\n\n log.info('Using the following numeric columns: {n}'.format(n=numeric_cols))\n log.info('Using the following categorical columns: {c}'.format(c=categorical_cols))\n\n return numeric_cols, categorical_cols, combined_cols, all_cols\n\n def _format_df_target(self, df, target):\n raise NotImplementedError\n\n # for binary classification:\n #df[target] = pd.get_dummies(df[target], drop_first=True) # converts the target to 1 or 0\n\n def _df_bin_max_categories(self, df, categorical_cols, max_categories):\n \"\"\" Cap the max number of categories in categorical fields for readability \"\"\"\n for col in categorical_cols:\n df[col].fillna(\"Unknown\", inplace = True)\n top_categories = df[col].value_counts().nlargest(max_categories-1).index\n # set values with ranked counts below max_categories to \"Other(Overflow)\"\n df.loc[~df[col].isin(top_categories), col] = \"Other(Overflow)\"\n \n return df\n\n def _rank_numeric_cols(self, df, target, numeric_cols):\n raise NotImplementedError\n\n def _rank_categorical_cols(self, df, target, categorical_cols):\n raise NotImplementedError\n\n def _is_listlike(self, parameter):\n return isinstance(parameter, (list, tuple, set, pd.Series, pd.Index))\n\n def _validate_min_numeric_cols(self, cols, min_cols):\n \"\"\" Validate that at least n colunms are numeric in cols list (n=min_cols)\"\"\"\n if cols is False: \n numeric_count = len(self.numeric_cols)\n else:\n numeric_count = len(set(cols).intersection(self.numeric_cols))\n if numeric_count < min_cols:\n raise ValueError(\"Need at least {n} numeric columns\".format(n=min_cols))\n\n def _validate_min_categorical_cols(self, cols, min_cols):\n \"\"\" Validate that at least n colunms are categorical in cols list (n=min_cols)\"\"\"\n if cols is False: \n categorical_count = len(self.categorical_cols)\n else:\n categorical_count = len(set(cols).intersection(self.categorical_cols))\n if categorical_count < min_cols:\n raise ValueError(\"Need at least {n} categorical columns\".format(n=min_cols)) \n\n\n def _balance_df(self, df, target):\n if self.eda_type == 'classification':\n count_class_0, count_class_1 = df[target].value_counts()\n class_0, class_1 = df[target].value_counts().index\n max_sample = min(count_class_0, count_class_1)\n\n df_class_0 = df[df[target] == class_0]\n df_class_1 = df[df[target] == class_1]\n df_class_0_under = df_class_0.sample(max_sample)\n df_class_1_under = df_class_1.sample(max_sample)\n\n df = pd.concat([df_class_0_under, df_class_1_under], axis=0)\n\n return df\n\n def _get_best_numeric_cols(self, cols, max_plots):\n \"\"\" Find top n ranked numeric columns in cols list (n=max_plots)\"\"\"\n self._validate_min_numeric_cols(cols, min_cols=1)\n ranked_plot_cols = [col for col in self._ranked_numeric_cols if col in cols]\n max_plots = max_plots if max_plots < len(ranked_plot_cols) else len(ranked_plot_cols)\n return ranked_plot_cols[0:max_plots]\n\n def _get_best_categorical_cols(self, cols, max_plots):\n \"\"\" Find top n ranked categorical columns in cols list (n=max_plots)\"\"\"\n self._validate_min_categorical_cols(cols, min_cols=1)\n ranked_plot_cols = [col for col in self._ranked_categorical_cols if col in cols]\n max_plots = max_plots if max_plots < len(ranked_plot_cols) else len(ranked_plot_cols)\n\n return ranked_plot_cols[0:max_plots]\n\n def _get_best_col_pairs(self, ranked_cols, max_plots):\n \"\"\" Find top n pairs of columns in ranked_cols list (n=max_plots)\"\"\"\n # n is how many columns are needed to satisfy the pairs criteria\n n=2; m=1;\n while m < max_plots:\n m += n\n n += 1 \n\n # if the number of columns is less than n, use them all\n if len(ranked_cols) <= n: n = len(ranked_cols)\n plot_cols = ranked_cols[0:n]\n weakest_col = plot_cols[n-1]\n\n # get all possible pairs \n col_pairs = list(itertools.combinations(plot_cols, 2))\n # remove the excess using the weakest column (the nth column)\n while len(col_pairs) > max_plots:\n i = 0\n for col_pair in col_pairs:\n if col_pair[0] == weakest_col or col_pair[1] == weakest_col:\n break\n i += 1\n col_pairs.pop(i)\n\n return col_pairs \n\n def _get_best_numeric_pairs(self, cols, max_plots):\n \"\"\" Find top n pairs of ranked numeric columns in cols list (n=max_plots)\"\"\"\n self._validate_min_numeric_cols(cols, min_cols=2)\n ranked_cols = [col for col in self._ranked_numeric_cols if col in cols]\n return self._get_best_col_pairs(ranked_cols, max_plots) \n\n def _get_best_categorical_pairs(self, cols, max_plots):\n \"\"\" Find top n pairs of ranked categorical columns in cols list (n=max_plots)\"\"\"\n self._validate_min_categorical_cols(cols, min_cols=2)\n ranked_cols = [col for col in self._ranked_categorical_cols if col in cols]\n return self._get_best_col_pairs(ranked_cols, max_plots) \n\n def _get_best_numeric_categorical_pairs(self, cols, max_plots):\n \"\"\" Find top n ranked pairs of (numeric, categorical) columns in cols list (n=max_plots)\"\"\"\n self._validate_min_categorical_cols(cols, min_cols=1)\n self._validate_min_numeric_cols(cols, min_cols=1)\n ranked_categorical_cols = [col for col in self._ranked_categorical_cols if col in cols]\n ranked_numeric_cols = [col for col in self._ranked_numeric_cols if col in cols]\n\n ## Find best numeric-categorical pairs based on correlation and logistic regression score\n # try to get an even split, preferring categorical\n num_categoricals = math.ceil(math.sqrt(max_plots))\n if num_categoricals > len(ranked_categorical_cols): num_categoricals = len(ranked_categorical_cols) \n num_numeric = math.ceil(max_plots/num_categoricals)\n if num_numeric > len(ranked_numeric_cols): num_numeric = len(ranked_numeric_cols) \n\n categorical_pair_cols = ranked_categorical_cols[0:num_categoricals]\n numeric_pair_cols = ranked_numeric_cols[0:num_numeric]\n\n weakest_numeric_col = numeric_pair_cols[num_numeric-1]\n\n cat_num_pairs = [pair for pair in itertools.product(numeric_pair_cols, categorical_pair_cols)]\n # if over max_plots limit, pop off pairs with the worst numerical col one at a time\n while len(cat_num_pairs) > max_plots:\n i = 0\n for col_pair in cat_num_pairs:\n if col_pair[0] == weakest_numeric_col or col_pair[1] == weakest_numeric_col:\n break\n i += 1\n cat_num_pairs.pop(i)\n\n return cat_num_pairs\n\n def _log_transform_df(self, df, log_transform):\n \"\"\" Take log base 10 of the specified columns in the log_transform parameter \"\"\"\n logged_cols = []\n\n # log_transform can be: True, a string, or an iterable of cols to transform\n if log_transform is True:\n transform_cols = self.numeric_cols.intersection(set(df.columns))\n elif isinstance(log_transform, str):\n transform_cols = [log_transform]\n elif self._is_listlike(log_transform):\n transform_cols = log_transform\n else: raise ValueError('Invalid argument to log_tranform parameter: {l}'.format(l=log_transform))\n\n for col in transform_cols:\n if col not in self.numeric_cols: \n log.warning(\"Unable to log transform non-numeric column: {c}\".format(c=col))\n\n for col in df:\n # only positive values can be logged\n if col in transform_cols and col in self.numeric_cols and min(df[col]) >= 0:\n df[col] = np.log10(df[col] + 1)\n logged_cols.append(col)\n elif col in transform_cols and col in self.numeric_cols and min(df[col]) < 0:\n log.warning(\"Unable to log transform column with negative values: {c}\".format(c=col))\n\n return df, logged_cols\n\n def _create_transformed_plot_df(self, plot_cols, log_transform):\n \"\"\" Create local copy of df for plot and log transform \"\"\"\n plot_df = self.df.copy()\n # wrap in DataFrame() to ensure single index doesn't become Series\n if self.target:\n plot_df = pd.DataFrame(plot_df[ list(plot_cols) + [self.target] ])\n else: plot_df = pd.DataFrame(plot_df[plot_cols])\n\n if log_transform: \n plot_df, logged_cols = self._log_transform_df(plot_df, log_transform)\n else: logged_cols = []\n\n return plot_df, logged_cols\n\n def _filter_cols_to_plot(self, possible_cols, specified_cols, exclude, filter_function, max_plots): \n \"\"\" Apply parameters specified by the user to find list of column/bivariates to plot \"\"\"\n if not isinstance(max_plots, int): raise ValueError('Max_plots must be an integer')\n\n if specified_cols: \n if isinstance(specified_cols, str):\n specified_cols = [specified_cols]\n if not self._is_listlike(specified_cols): \n raise ValueError('Invalid cols argument: {c}'.format(c=specified_cols))\n invalid_col = list(set(specified_cols) - self.all_cols)\n if len(invalid_col) > 0:\n log.error('Invalid colums passed to cols parameter: {i}'.format(i=invalid_col))\n possible_cols = specified_cols\n\n if exclude:\n if isinstance(exclude, str):\n exclude = [exclude]\n if not self._is_listlike(exclude): \n raise ValueError('Invalid cols argument: {c}'.format(c=exclude))\n invalid_exclude = list(set(exclude) - self.combined_cols)\n if len(invalid_exclude) > 0:\n log.error('Invalid colums passed to exclude parameter: {i}'.format(i=invalid_exclude))\n if self.target and self.target in exclude: log.warning(\"Can't exclude target column\")\n possible_cols = [col for col in possible_cols if col not in exclude]\n\n cols_to_plot = filter_function(possible_cols, max_plots)\n return cols_to_plot\n\n def _param_plot_categorical(self, cols=False, exclude=None, max_plots=150, chart_params=None):\n \"\"\" Plot the catgegorical columns against target (if provided) \"\"\"\n plot_cols = self._filter_cols_to_plot(\n possible_cols = self.categorical_cols, \n specified_cols = cols, \n exclude = exclude, \n filter_function = self._get_best_categorical_cols, \n max_plots = max_plots\n )\n self._validate_min_categorical_cols(plot_cols, min_cols=1)\n \n for col in plot_cols:\n self._plot_categorical_col(col=col, chart_params=chart_params)\n\n def _param_plot_numeric(\n self, \n cols=False, \n exclude=None, \n max_plots=150, \n log_transform=False, \n chart_params=None\n ):\n \"\"\" Plot the numeric columns against target (if provided) \"\"\"\n plot_cols = self._filter_cols_to_plot(\n possible_cols = self.numeric_cols, \n specified_cols = cols, \n exclude = exclude, \n filter_function = self._get_best_numeric_cols, \n max_plots = max_plots\n )\n self._validate_min_numeric_cols(plot_cols, min_cols=1)\n plot_df, logged_cols = self._create_transformed_plot_df(plot_cols, log_transform)\n\n for col in plot_cols:\n self._plot_numeric_col(\n plot_df = plot_df, \n col = col, \n logged_cols = logged_cols, \n chart_params = chart_params,\n )\n\n def _param_plot_numeric_pairs(\n self, \n cols=False, \n exclude=None, \n log_transform=False, \n max_plots=40, \n chart_params=None\n ):\n \"\"\" Plot pairs of numeric columns colored by target (if provided)\"\"\"\n numeric_pairs = self._filter_cols_to_plot(\n possible_cols = self.numeric_cols, \n specified_cols = cols, \n exclude = exclude, \n filter_function = self._get_best_numeric_pairs, \n max_plots = max_plots\n )\n plot_cols = set([col for pair in numeric_pairs for col in pair])\n self._validate_min_numeric_cols(plot_cols, min_cols=2)\n plot_df, logged_cols = self._create_transformed_plot_df(plot_cols, log_transform)\n if chart_params['balance'] is True: \n plot_df = self._balance_df(plot_df, self.target)\n \n for pair in numeric_pairs:\n self._plot_numeric_pair(\n plot_df = plot_df, \n pair = pair, \n logged_cols = logged_cols, \n chart_params = chart_params,\n )\n\n def _param_plot_categorical_pairs(self, cols=False, exclude=None, max_plots=50, chart_params=None):\n \"\"\" Plot pairs categorical columns against the target \"\"\"\n categorical_pairs = self._filter_cols_to_plot(\n possible_cols = self.categorical_cols, \n specified_cols = cols, \n exclude = exclude, \n filter_function = self._get_best_categorical_pairs, \n max_plots = max_plots\n )\n plot_cols = set([col for pair in categorical_pairs for col in pair])\n self._validate_min_categorical_cols(plot_cols, min_cols=2)\n \n for pair in categorical_pairs:\n self._plot_categorical_pair(pair=pair, chart_params=chart_params)\n\n def _param_plot_numeric_categorical_pairs(\n self, \n cols=False, \n exclude=None, \n log_transform=False,\n max_plots=40,\n chart_params=None\n ):\n \"\"\" Plot pairs of numeric vs categorical columns broken down by the target \"\"\"\n self._validate_min_categorical_cols(cols, min_cols=1)\n self._validate_min_numeric_cols(cols, min_cols=1)\n \n num_cat_pairs = self._filter_cols_to_plot(\n possible_cols = self.combined_cols, \n specified_cols = cols, \n exclude = exclude, \n filter_function = self._get_best_numeric_categorical_pairs, \n max_plots = max_plots\n )\n plot_cols = set([col for pair in num_cat_pairs for col in pair])\n plot_df, logged_cols = self._create_transformed_plot_df(plot_cols, log_transform)\n\n for pair in num_cat_pairs:\n self._plot_numeric_categorical_pair(\n plot_df = plot_df, \n pair = pair, \n logged_cols = logged_cols, \n chart_params = chart_params,\n )\n\n def plot_pca(self, output_components=None):\n \"\"\" Perform PCA and plot variability described the PCs \"\"\"\n if len(self.numeric_cols) < 2: raise ValueError('Need at least 2 numeric cols for PCA')\n pca_df = self.df[self.numeric_cols].copy()\n \n imp=SimpleImputer(missing_values=np.NaN)\n imp_df=pd.DataFrame(imp.fit_transform(pca_df))\n \n pca = PCA(n_components=imp_df.shape[1])\n pca.fit(imp_df)\n\n ## Output error explained by sqrt(n)th term\n if not output_components: output_components = math.floor(math.sqrt(imp_df.shape[1]))\n\n ## Inspect the explained variances to determine how many components to use \n plt.subplots(figsize=(8, 8))\n # use n_components series to make x axis start at 1\n n_components = pd.Series(range(1,len(np.cumsum(pca.explained_variance_ratio_))+1))\n plt.plot(n_components, np.cumsum(pca.explained_variance_ratio_))\n plt.xlabel('Number of Components')\n plt.ylabel('Cumulative Explained Variance')\n\n ## Output the explained variances at output_components # of components\n output_str = 'Cumulative Explained variance at {n} PCA components:'.format(n=output_components)\n print(output_str,sum(pca.explained_variance_ratio_[0:output_components]) )\n \n def plot_corr_heatmap(self, annot=False, figsize=(10,10)):\n \"\"\" Plot grid of numeric columns with a heat map of their correlations \"\"\"\n if len(self.numeric_cols) < 2: raise ValueError('Need at least 2 numeric cols for corr heatmap')\n df_numeric = self.df[self.numeric_cols]\n\n fig, ax = plt.subplots(figsize=figsize)\n sns.heatmap(df_numeric.corr(), annot=annot, ax=ax)\n\n def _plot_categorical_col(self, col, chart_params):\n raise NotImplementedError\n\n def _plot_numeric_col(self, plot_df, col, chart_params, logged_cols):\n raise NotImplementedError\n\n def _plot_numeric_pair(self, plot_df, pair, chart_params, logged_cols):\n raise NotImplementedError\n\n def _plot_categorical_pair(self, pair, chart_params):\n raise NotImplementedError\n\n def _plot_numeric_categorical_pair(self, plot_df, pair, chart_params, logged_cols):\n raise NotImplementedError\n\n\n\n\n\nclass ClassificationEDA(autoEDA):\n def __init__(self, df, target=None, max_categories=None):\n super().__init__(df=df, target=target, max_categories=max_categories, eda_type='classification')\n\n def _validate_input_target(self, df, target):\n if not isinstance(target, str): raise ValueError('Invalid target: {t}'.format(t=target))\n if df[target].nunique() != 2: raise ValueError('Target must have 2 unique values')\n\n def _format_df_target(self, df, target):\n df[target] = pd.get_dummies(df[target], drop_first=True) # converts the target to 1 or 0\n return df\n\n def _rank_numeric_cols(self, df, target, numeric_cols):\n correlations = [(col, abs(self.df[self.target].corr(self.df[col]))) for col in self.numeric_cols]\n correlations.sort(key=lambda tup: tup[1], reverse=True)\n ranked_numeric_cols = [col_corr[0] for col_corr in correlations]\n \n return ranked_numeric_cols\n\n def _rank_categorical_cols(self, df, target, categorical_cols):\n \"\"\" Run small batch of logistic regression against target with each categorical col to rank \"\"\"\n sample_df = self.df.copy()\n if self.df.shape[0] > 1000: sample_df = self.df.sample(n=1000)\n\n col_scores = []\n for col in self.categorical_cols:\n y = sample_df[self.target]\n try:\n X_onehot = pd.get_dummies(sample_df[col], drop_first=True)\n except:\n pdb.set_trace()\n\n lr = LogisticRegression(n_jobs=-1, max_iter=999)\n try:\n lr.fit(X_onehot,y)\n except:\n pdb.set_trace()\n y_pred = lr.predict(X_onehot)\n acc = accuracy_score(y_pred, y)\n\n col_scores.append((col, acc))\n\n # rank based on training set accuracy\n col_scores.sort(key=lambda tup: tup[1], reverse=True)\n ranked_categorical_cols = [col_corr[0] for col_corr in col_scores]\n \n return ranked_categorical_cols\n\n\n def _plot_categorical_col(self, col, chart_params):\n \"\"\" Charts the counts of caterogical cols with % of binary response overlaid \"\"\"\n verbose = True if 'verbose' in chart_params and chart_params['verbose'] else False\n\n field_count = self.df[col].value_counts()\n field_count_df = field_count.to_frame()\n field_count_df.columns = ['count']\n\n # Get the % target by category for the line overlay\n field_target_pct = pd.crosstab(self.df[col], self.df[self.target], normalize='index') * 100\n field_target_pct = field_target_pct.reset_index()\n # Try to choose the axis with smaller values to avoid skewed axis\n if not self._bar_lineplot_reference:\n self._bar_lineplot_reference = 1 if field_target_pct[0].median() < field_target_pct[1].median() else 2\n drop_index = self._bar_lineplot_reference\n field_target_pct = field_target_pct.drop(field_target_pct.columns[-drop_index],axis=1)\n\n merged_filed_target_pct = field_target_pct.merge(field_count_df, right_index=True, left_on=col)\n field_target_data = merged_filed_target_pct.sort_values('count', ascending=False).reset_index(drop=True)\n if verbose : print(field_target_data)\n\n fig, ax = plt.subplots(figsize=(10, 6))\n ax.set_xlabel(col)\n ax = sns.barplot(\n field_target_data[col], \n field_target_data['count'], \n alpha=0.8,\n order = field_target_data.sort_values('count', ascending=False)[col]\n )\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right')\n ax.set_ylabel('count (bars)')\n ax2 = ax.twinx() # dual axis graph\n # line graph of % target in category\n ax2 = sns.pointplot(\n x=field_target_data[col], \n y=field_target_data.iloc[:,-2], \n color='black', \n legend=False\n )\n ax2.set_ylabel('% {t} (line)'.format(t = self.target))\n plt.show()\n\n def _plot_numeric_col(self, plot_df, col, chart_params, logged_cols):\n bins = chart_params['bins']\n\n # prefix 'log_' to the colunm name if it was log transformed\n target_value0 = plot_df[self.target].value_counts().index[0]\n target_value1 = plot_df[self.target].value_counts().index[1]\n\n col_name = 'log_{c}'.format(c=col) if col in logged_cols else col\n fig, ax = plt.subplots(figsize=(10, 6))\n\n sns.distplot(\n plot_df.loc[plot_df[self.target] == target_value0][col],\n label=target_value0, \n bins = bins, \n )\n sns.distplot(\n plot_df.loc[plot_df[self.target] != target_value0][col],\n label=target_value1, \n bins = bins, \n )\n ax.legend(loc='upper right')\n ax.set_title('{c} histogram'.format(c=col_name))\n\n def _plot_numeric_pair(self, plot_df, pair, chart_params, logged_cols):\n alpha = chart_params['alpha']\n\n fig, ax = plt.subplots(figsize=(10, 6))\n prefix0 = 'log_' if pair[0] in logged_cols else ''\n prefix1 = 'log_' if pair[1] in logged_cols else ''\n title = '{p0}{f0} vs {p1}{f1}'.format(p0=prefix0, f0=pair[0], p1=prefix1, f1=pair[1])\n \n sns.scatterplot(\n data=plot_df, \n x=pair[0], \n y=pair[1], \n hue=plot_df[self.target].tolist(), \n alpha=alpha, \n )\n ax.set_title(title)\n\n def _plot_categorical_pair(self, pair, chart_params):\n annot = chart_params['annot']\n\n fig, ax = plt.subplots(figsize=(10, 6))\n sns.heatmap(\n pd.pivot_table(self.df,index=[pair[0]], values=self.target, columns=[pair[1]]),\n annot=annot,\n ) \n\n def _plot_numeric_categorical_pair(self, plot_df, pair, chart_params, logged_cols):\n boxplot_only = chart_params['boxplot_only']\n\n fig, ax = plt.subplots(figsize=(10, 6))\n # prefix 'log_' to the colunm name if it was log transformed\n numeric_col_name = 'log_{c}'.format(c=pair[0]) if pair[0] in logged_cols else pair[0]\n title = '{c} vs {n}'.format(c=pair[1], n=numeric_col_name)\n\n category_count = len(self.df[pair[1]].value_counts())\n if category_count <= 15 and not boxplot_only:\n sns.violinplot(\n x=pair[1], \n y=pair[0], \n hue=self.target, \n data=plot_df, \n split=True, \n inner='quart',\n )\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right')\n else:\n sns.boxplot(x=pair[1], y=pair[0], hue=self.target, data=plot_df)\n\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right')\n ax.set_title(title)\n\n def plot_categorical(\n self, \n cols=False, \n exclude=None, \n max_plots=150, \n verbose=False\n ):\n if verbose is not True and verbose is not False:\n log.error('Invalid verbose parameter, choose True or False')\n verbose = False\n\n chart_params = {}\n chart_params['verbose'] = verbose\n self._param_plot_categorical(\n cols=cols, \n exclude=exclude, \n max_plots=max_plots, \n chart_params=chart_params\n )\n\n def plot_numeric(\n self, \n cols=False, \n exclude=None, \n max_plots=150,\n log_transform=False,\n bins=None\n ):\n if bins is not None and not isinstance(bins, int):\n log.error('Invalid bins parameter, must be int')\n bins = None\n\n chart_params = {}\n chart_params['bins'] = bins\n self._param_plot_numeric(\n cols=cols, \n exclude=exclude, \n max_plots=max_plots,\n log_transform=log_transform,\n chart_params=chart_params\n )\n\n def plot_scatterplots(\n self, \n cols=False, \n exclude=None, \n max_plots=150,\n log_transform=False,\n alpha=0.6,\n balance=False,\n ):\n if alpha is not None and not isinstance(alpha, float):\n log.error('Invalid bins parameter, must be float')\n alpha = 0.6\n if balance is not False and balance is not True:\n log.error('Invalid balance parameter, must be True/False')\n balance=False\n\n chart_params = {}\n chart_params['alpha'] = alpha\n chart_params['balance'] = balance\n self._param_plot_numeric_pairs(\n cols=cols, \n exclude=exclude, \n max_plots=max_plots,\n log_transform=log_transform,\n chart_params=chart_params\n )\n\n def plot_categorical_pairs(\n self, \n cols=False, \n exclude=None, \n max_plots=150,\n annot=False\n ):\n if annot is not False and annot is not True:\n log.error('Invalid annot parameter, must be True/False')\n annot = False\n\n chart_params = {}\n chart_params['annot'] = annot\n self._param_plot_categorical_pairs(\n cols=cols, \n exclude=exclude, \n max_plots=max_plots,\n chart_params=chart_params\n )\n def plot_numeric_categorical_pairs(\n self, \n cols=False, \n exclude=None, \n max_plots=150,\n log_transform=False,\n boxplot_only=False\n ):\n if boxplot_only is not False and boxplot_only is not True:\n log.error('Invalid boxplot_only parameter, must be True/False')\n boxplot_only = False\n\n chart_params = {}\n chart_params['boxplot_only'] = boxplot_only\n self._param_plot_numeric_categorical_pairs(\n cols=cols, \n exclude=exclude, \n max_plots=max_plots,\n log_transform=log_transform,\n chart_params=chart_params\n )\n ","sub_path":"autoEDA.py","file_name":"autoEDA.py","file_ext":"py","file_size_in_byte":30897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"633369283","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n'''\r\nurl_from_out을 매개변수로 받은 뒤에 soup객체와 함께 페이지의 소스코드를 텍스트화시킨 html_info를 제공받는다. \r\n그후 soup객체를 가공해서 리스트로 만든 뒤 soup_str_translate을 반환한다. \r\nurl_list라는 리스트를 생성하는데 페이지에 존재하는 모든 링크를 리스트에 할당한다. \r\n동시에 http를 포함하는 문자열 중에서 exe가 포함되지 않은 문자열을 url_list라는 리스트로 반환한다. \r\n\r\nfor link in soup.find_all('a'):\r\n print(link.get('href')) \r\n\r\n--> 을 사용하면 쉽게 하이퍼링크만 뽑아낼 수 있다. 근데 이 기능만 사용하면 exe파일과 같이 다른 페이지로 \r\n넘어가는 link가 아닌 다른 link들도 함께 sorting된다. 그러므로 따로 조건을 더 달아줘야함. \r\n'''\r\n\r\ndef to_text(url_from_out):\r\n url = url_from_out \r\n html_info = requests.get(url).text \r\n soup = BeautifulSoup(html_info,'html.parser') \r\n\r\n soup_text = soup.get_text() #soup객체를 텍스트로 만들어서 soup_text에 할당하기. \r\n soup_str_translate = soup_text.split() #soup_text객체를 공백 구분해서 soup_str_translate에 할당. \r\n\r\n url_list = [] #모든 링크는 url_list의 리스트를 통해 접근 가능하다. \r\n for link in soup.find_all('a'): #soup객체 내에 존재하는 모든 링크를 list로 만들어준다. \r\n url_list.append(link.get('href'))\r\n \r\n\r\n new_url_list = [] #새로운 리스트를 생성해서 가공된 url list를 할당한다. \r\n for i in range(len(url_list)): \r\n try:\r\n #http가 있는 문자열 즉 연결 가능한 링크만 따로 모아서 new_url_list에 할당한다.\r\n #가끔 None을 반환하는 링크가 있다. 그럴 경우는 제외시킨다. \r\n #exe 파일도 제외시킨다. \r\n if ((url_list[i][0:4] == \"http\") & (url_list[i] != None)): \r\n if \"exe\" not in url_list[i]: #실행파일이 아닌 경우에만\r\n new_url_list.append(url_list[i]) \r\n except TypeError: #TypeError가 발생하는 경우가 있음. 그럴 경우에는 무시하고 진행\r\n continue\r\n\r\n #해당되는 기호들이 있으면 제거한다. word_list에 정리된 단어들을 할당한다. \r\n word_list = []\r\n for word in soup_str_translate:\r\n symbols = \"\"\"▶↑~!@#$%^&*()_-+={[}]|\\\\;:\"‘'·<>?/.,ⓒ \"\"\" \r\n for i in range(len((symbols))):\r\n\r\n #해당 symbols내의 기호가 있으면 '' 내부의 것으로 바꾼다. \r\n #근데 '' 안에 아무것도 없으니 제거하는것과 마찬가지 기능을 함. \r\n word = word.replace(symbols[i], '') \r\n\r\n if len(word) > 0:\r\n word_list.append(word)\r\n \r\n return word_list,new_url_list #가공된 word에 관한 리스트와 url에 관한 리스트를 반환시켜 준다. 2개 반환..\r\n","sub_path":"bs4/collect_text.py","file_name":"collect_text.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"295035630","text":"import asyncio\nimport time\n\nasync def me_first() -> str:\n await asyncio.sleep(1)\n\n return \"I'm first!\"\n\nasync def me_second() -> str:\n await asyncio.sleep(1)\n\n return \"Then me!\"\n\nasync def me_third() -> str:\n await asyncio.sleep(1)\n\n return \"And finally me!\"\n\nasync def main():\n start = time.perf_counter()\n\n first_result = await me_first()\n second_result = await me_second()\n third_result = await me_third()\n\n end = time.perf_counter()\n\n print(f\"It took {end - start} seconds to complete all operations\\n\")\n\n print(first_result)\n print(second_result)\n print(third_result)\n\n\nasyncio.run(main())","sub_path":"src/coroutine-4.py","file_name":"coroutine-4.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"185853758","text":"from spack import *\n\n\nclass Lgrtk(CMakePackage):\n \"\"\"LGRTK is a tool kit for using the Lagrangian Grid Reconnection\n method to build simulations.\n \"\"\"\n\n homepage = \"https://github.com/SNLComputation/lgrtk\"\n url = \"https://github.com/SNLComputation/lgrtk/archive/v0.0.0.tar.gz\"\n git = \"git@github.com:SNLComputation/lgrtk.git\"\n\n version('master', branch='master')\n\n variant('tests', default=True, description='Compile tests')\n variant('cubit', default=False, description='Point to CUBIT for inline meshing')\n\n depends_on('omega-h')\n depends_on('cubit', when='+cubit')\n depends_on('googletest~pthreads', when='+tests')\n\n def cmake_args(self):\n args = []\n args.append('-DCMAKE_BUILD_TYPE:STRING=')\n args.append('-DBUILD_SHARED_LIBS:BOOL=ON')\n if '+tests' in self.spec:\n args.append('-DBUILD_TESTING:BOOL=ON')\n args.append('-DGTest_PREFIX:PATH={0}'.format(\n self.spec['googletest'].prefix))\n else:\n args.append('-DBUILD_TESTING:BOOL=OFF')\n args.append('-DOmega_h_PREFIX:PATH={0}'.format(\n self.spec['omega-h'].prefix))\n return args\n\n def flag_handler(self, name, flags):\n flags = list(flags)\n if name == 'cxxflags':\n flags.append(self.compiler.cxx11_flag)\n return (None, None, flags)\n\n def root_cmakelists_dir(self):\n return os.path.join(self.stage.source_path, 'v2')\n","sub_path":"packages/lgrtk/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"11639925","text":"import ssl\nimport argparse\nimport OpenSSL\nparser=argparse.ArgumentParser(description='Process args for Host')\nparser.add_argument('-i', type=str, dest='ip', required=True)\nparser.add_argument('-o', type=int ,dest=\"port\", required=False, default=443)\nargs=parser.parse_args()\n\naddr = (args.ip, args.port)\npem = ssl.get_server_certificate(addr)\n\nthumbprint = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, pem)\nbigprint = thumbprint.digest('sha1')\n\n\nprint(bigprint)\n","sub_path":"Thumb.py","file_name":"Thumb.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"317483774","text":"from flask import (\n Blueprint,\n redirect,\n render_template,\n url_for,\n request,\n session\n)\nbp = Blueprint('main', __name__)\n\nfrom app.controllers.User import UserForm\n\n@bp.route('/', methods=['GET','POST'])\ndef home():\n form = UserForm(request.form)\n if request.method == \"POST\":\n return 'ok'\n return render_template('main/index.html', form=form)\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"607575971","text":"# **=\t幂赋值运算符\tc **= a 等效于 c = c ** a\n# //=\t取整除赋值运算符\tc //= a 等效于 c = c // a\n\na = 21\nb = 10\nc = 2\n\nc **= a\nprint(\"6 - c 的值为:\", c)\n\nc //= a\nprint(\"7 - c 的值为:\", c)\n\n# 逻辑运算符\n\n# and or not\n\n# 成员运算符\n# in\t如果在指定的序列中找到值返回 True,否则返回 False。\tx 在 y 序列中 , 如果 x 在 y 序列中返回 True。\n# not in\t如果在指定的序列中没有找到值返回 True,否则返回 False。\tx 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。\n\na = 10\nb = 20\nlist = [1, 2, 3, 4, 5];\n\nif (a in list):\n print(\"1 - 变量 a 在给定的列表中 list 中\")\nelse:\n print(\"1 - 变量 a 不在给定的列表中 list 中\")\n\nif (b not in list):\n print(\"2 - 变量 b 不在给定的列表中 list 中\")\nelse:\n print(\"2 - 变量 b 在给定的列表中 list 中\")\n\n# 身份运算符用于比较两个对象的存储单元\n# is 是判断两个标识符是不是引用自一个对象\tx is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False\n# is not 是判断两个标识符是不是引用自不同对象\tx is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。\n# id() 函数用于获取对象内存地址。\n\n# is 与 == 区别:\n# is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。\n\na = [1, 2, 3]\nb = a\nprint(b is a);\n# True\nprint(b == a);\n# True","sub_path":"basic/7_operator.py","file_name":"7_operator.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"643439962","text":"from api import *\nfrom utils.pastebins import *\n\ndef load():\n \"\"\"Records books for the gentoolib v2.\"\"\"\n dbExecute('''create table if not exists books (\n book_id int auto_increment primary key,\n title text, \n added_by varchar(255) )\n ''')\nregisterModule('Books', load)\n\n@register(\"addbook %S\", syntax=\"addbook booktitle\")\ndef addBook(channel, sender, booktitle):\n \"\"\"Store the book in the database\"\"\"\n if booktitle == \"\":\n sendMessage(sender, \"Enter a proper book title. syntax: addbook booktitle\")\n return\n else:\n log.info('Trying to insert book: %s' % booktitle)\n dbExecute('INSERT INTO books (title, added_by) VALUES (%s, %s)', [booktitle, sender])\n sendMessage(channel, \"Book recorded\")\n\n@register(\"dumpbooks\", syntax=\"dumpbooks\")\ndef allBooks(channel, sender):\n \"\"\"Fetches all books in database, upload them on a pastebin, not featured not scalable fuckyou\"\"\"\n books = dbQuery('SELECT title, added_by FROM books')\n bookList = ''\n for (title, added_by) in books:\n bookList += '\\\"%s\\\" inserted by \\\"%s\\\"\\n' % (title, added_by)\n try:\n url = paste(bookList)\n except Exception:\n sendMessage(channel, \"Uploading book list failed.\")\n return\n sendMessage(channel, \"%s, Books: %s\" % (sender, url))\n","sub_path":"modules/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"404624339","text":"'''\nGiven a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.\n\nNote:\n\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\nExample 1:\n\nInput: [2,2,3,2]\nOutput: 3\nExample 2:\n\nInput: [0,1,0,1,0,1,99]\nOutput: 99\n\n\nSOLUTION LOGIC 1:\nWe can sum the bits in same positions for all the numbers and take modulo with 3. The bits for which sum is not multiple of 3, are the bits of number with single occurrence.\nLet us consider the example array {5, 5, 5, 8}. The 101, 101, 101, 1000\nSum of first bits%3 = (1 + 1 + 1 + 0)%3 = 0;\nSum of second bits%3 = (0 + 0 + 0 + 0)%0 = 0;\nSum of third bits%3 = (1 + 1 + 1 + 0)%3 = 0;\nSum of fourth bits%3 = (1)%3 = 1;\nHence number which appears once is 1000\n\n'''\nINT_SIZE = 4\ndef single_number(nums) -> int:\n print(nums)\n result = 0\n for i in range(0,INT_SIZE):\n sm = 0\n x = (1 << i)\n for j in range(0,len(nums)):\n print(nums[j],x,nums[j]&x)\n if (nums[j] & x):\n sm += 1\n\n\nif __name__ == '__main__':\n input = [2,2,3,2]\n print(single_number(input))\n","sub_path":"SingleNumberLeet.py","file_name":"SingleNumberLeet.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"69330112","text":"import pandas as pd\nimport numpy as np\nimport pickle\n\n\ndef pickle_read(path):\n with open(path, \"rb\") as f:\n pickle_file = pickle.load(f)\n return pickle_file\n\ndef pickle_write(item, path):\n with open(path, \"wb\") as f:\n pickle.dump(item, f)\n\ndef increasing_debt(row, column, i):\n if i > 1 and row[column + f'{i}'] < row[column + f'{i - 1}'] and row[\"is_streak\"] == 1:\n row[\"debt_streak\"] += 1\n row[\"raw_debt_accum\"] += row[column + f'{i - 1}'] - row[column + f'{i}']\n else:\n row[\"is_streak\"] = 0\n return row\n\n\ndef initiate_placeholders(df):\n df[\"is_streak\"], df[\"debt_streak\"] = 1, 0\n df[\"raw_debt_accum\"] = 0\n return df\n\n\ndef remove_placeholders(df):\n return df.drop(columns=[\"is_streak\", \"raw_debt_accum\"])\n\n\ndef replace_unknowns(df):\n education_dict = {4: 0, 5: 0, 6: 0}\n marriage_dict = {3: 0}\n df[\"EDUCATION\"].replace(education_dict, inplace=True)\n df[\"MARRIAGE\"].replace(marriage_dict, inplace=True)\n return df\n\ndef exclude_columns(looped_cols, start, end):\n \"\"\"Gathers column names to exclude\"\"\"\n looped_exc = []\n for col in looped_cols:\n sing_exc = [col + f\"{i}\" for i in np.arange(start, end)]\n looped_exc.extend(sing_exc)\n return looped_exc\n\n\ndef extract_dummies(df, column, value):\n \"\"\"Creates a column with dummy variables for matches in a value\"\"\"\n\n if np.isnan(value):\n return np.where(df[column].isna().values == True, 1, 0)\n else:\n return np.where(df[column].values == value, 1, 0)\n\n\ndef calculate_utilization(df):\n df[\"avg_utilization\"], df[\"avg_payment_impact\"] = 0, 0\n initiate_placeholders(df)\n for i in np.arange(1, 7):\n df['payment_impact' + f'{i}'] = (df['PAY_AMT' + f'{i}']) / df[\"LIMIT_BAL\"]\n df[\"utilization\" + f'{i}'] = df[\"BILL_AMT\" + f'{i}'] / df[\"LIMIT_BAL\"]\n if i > 1:\n df = df.apply(lambda x: increasing_debt(x, \"utilization\", i), axis=1)\n df[\"avg_utilization\"] += df[\"utilization\" + f'{i}']\n df[\"avg_payment_impact\"] += df[\"payment_impact\" + f'{i}']\n df[\"avg_utilization\"] = df[\"avg_utilization\"] / 6\n df[\"avg_payment_impact\"] = df[\"avg_payment_impact\"] / 6\n df[\"debt_avg_delta\"] = (df[\"raw_debt_accum\"] / df[\"debt_streak\"]).fillna(0)\n df = remove_placeholders(df)\n return df\n\n\ndef split_pay_columns(df):\n \"\"\"Extracts the quantitative information (The number of months of missed payments)\n from the qualitative, the two fields that determined ontime payments\"\"\"\n\n df = df.copy()\n for i in np.arange(0, 1):\n column = \"PAY_\" + f\"{i}\"\n df[column] = df[column].astype(int)\n dflt = df[column].unique().tolist()\n default_vals = dict(zip(dflt, dflt))\n default_vals[-1], default_vals[-2] = 0, 0\n df[f\"{column}N1\"] = extract_dummies(df, column, -1)\n df[f\"{column}N2\"] = extract_dummies(df, column, -1)\n df[column] = df[column].map(default_vals)\n return df\n\ndef combine_pay_columns(df):\n \"\"\"Extracts non correlated information from the past history pay columns. Any\n time there is an improvement to this field it is incremented and the sum is added\n to a new column in the dataframe.\"\"\"\n\n df = df.copy()\n before= df[\"PAY_0\"].values\n results = np.zeros(before.size)\n for i in np.arange(2, 7):\n column = \"PAY_\" + f\"{i}\"\n after = df[column].values\n comparison = before < after\n results += comparison.astype(int)\n df[\"payment_improvements\"] = results\n return df","sub_path":"week_7/classification-assessment/working_dir/data_cleaning.py","file_name":"data_cleaning.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"314469489","text":"# -*- coding: utf-8 -*-\r\n\r\nclass ProgressBar(object):\r\n\tdef __init__(self, title, \r\n\t\t\t\tcount = 0.0,\r\n\t\t\t\trun_status = None,\r\n\t\t\t\tfin_status = None,\r\n\t\t\t\ttotal = 100.0,\r\n\t\t\t\tunit = '',\r\n\t\t\t\tseq = '/',\r\n\t\t\t\tchunk_size = 1.0):\r\n\t\tsuper(ProgressBar, self).__init__()\r\n\t\tself.info = '【%s】%s %.2f %s %s %.2f %s'\r\n\t\tself.title = title \r\n\t\tself.total = total \r\n\t\tself.count = count \r\n\t\tself.chunk_size = chunk_size\r\n\t\tself.status = run_status or '' \r\n\t\tself.fin_status = fin_status or ' ' * len(self.status)\r\n\t\tself.unit = unit \r\n\t\tself.seq = seq\r\n\t\r\n\t\r\n\tdef __get_info(self):\r\n\t\t# 【名称】状态 进度 单位 分割线 总数 单位\r\n\t\t_info = self.info % (self.title, self.status, self.count/self.chunk_size,\r\n\t\t\tself.unit, self.seq, self.total/self.chunk_size, self.unit)\r\n\t\treturn _info \r\n\t\r\n\tdef refresh(self, count = 1, status = None):\r\n\t\tself.count += count \r\n\t\t# 状态不为空\r\n\t\tself.status = status or self.status \r\n\t\tend_str = '\\r'\r\n\t\tif self.count >= self.total:\r\n\t\t\tend_str = '\\n'\r\n\t\t\tself.status = status or self.fin_status \r\n\t\tprint(self.__get_info(), end=end_str)","sub_path":"CET6-spider/progressBar.py","file_name":"progressBar.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"42037973","text":"from ..grid.grid import Grid\n\n\ndef get_closest_point(grid, srce, dest, avoid_ennemies = False):\n if avoid_ennemies:\n offsets = Grid.get_closest_points(srce,dest)\n idx = 0\n while ([srce[0] + offsets[idx][0], srce[1] + offsets[idx][1]] not in grid.get_range(srce) or [srce[0] + offsets[idx][0], srce[1] + offsets[idx][1]] in grid.get_ennemy_range()) and idx < len(offsets)-1:\n idx += 1\n return srce[0] + offsets[idx][0], srce[1] + offsets[idx][1]\n else:\n if srce[0] < dest[0]:\n return srce[0] + 1, srce[1]\n elif srce[0] > dest[0]:\n return srce[0] - 1, srce[1]\n elif srce[1] < dest[1]:\n return srce[0], srce[1] + 1\n else:\n return srce[0], srce[1] - 1","sub_path":"algorithm/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"586569430","text":"from django.conf.urls import url\nfrom django.urls import path\nfrom .views import HomeView, ArticleDetailView, AddPostView,UpdatePostView,DeletePostView,AddCategoryView,CategoryView,CategoryListView,AddCommentView,DeleteCommentView\n\napp_name = 'blog'\n\nurlpatterns = [\n \n url(r'^$', HomeView.as_view(), name=\"home\"),\n url(r'^article/(?P\\d+)$', ArticleDetailView.as_view(), name='article-detail'),\n url(r'^add_post/$', AddPostView.as_view(), name='add-post'),\n url(r'^add_category/$', AddCategoryView.as_view(), name='add-category'),\n url(r'^article/edit/(?P\\d+)$', UpdatePostView.as_view(), name='update-post'),\n url(r'^article/(?P\\d+)/remove$', DeletePostView.as_view(), name='delete-post'),\n #url(r'^category/', CategoryView, name='category'),\n path('category//', CategoryView, name='category'),\n #path('category-list', CategoryListView, name='category-list'),\n url(r'^category-list/$', CategoryListView, name='category-list'),\n url(r'^article/(?P\\d+)/comment$', AddCommentView.as_view(), name='add-comment'),\n url(r'^comment/(?P\\d+)$', DeleteCommentView.as_view(), name='delete-comment'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"565472249","text":"import time\n\n\ndef show_date_time():\n print(time.asctime())\n\ndef countdown(t): \n \n while t: \n mins, secs = divmod(t, 60) \n timer = '{:02d}:{:02d}'.format(mins, secs) \n print(timer, end=\"\\r\") \n time.sleep(1) \n t -= 1\n print(\"Time Is Finished\")\n \ndef set_timer():\n Time = int(input(\"Enter the time in a second : \"))\n countdown(Time)\n\ndef count():\n print('Press \"Ctrl + z\" to stop time')\n t = 1\n while True: \n mins, secs = divmod(t, 60) \n timer = '{:02d}:{:02d}'.format(mins, secs) \n print(timer, end=\"\\r\") \n time.sleep(1) \n t += 1\n\ndef main():\n print(\"1.) Show Date And Time\")\n print(\"2.) Set Timer\")\n print(\"3.) Stop Watch\")\n \n user = int(input(\"Choose Options : \"))\n if(user==1):\n show_date_time()\n elif(user==2):\n set_timer()\n elif(user==3):\n count()\n else:\n print(\"invalid key pressed\")\nmain()\n","sub_path":"Clock.py","file_name":"Clock.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"5860188","text":"# -*- coding:gb2312 -*-\r\n# -*- $Id: itemmanager.py 2 2009-04-20 03:10:36Z fengyu05 $ -*-\r\n\r\nimport random\r\nimport math\r\nimport gamectrl.const as const\r\n\r\n\r\nclass ItemType(object):\r\n\r\n\tdef __init__(self, type=0, rate=10, contain=500, life=300, last_time=0,usage=False, name=\"\"):\r\n\t\tself.type = type # 加或者减, 0减, 1加\r\n\t\tself.speed = const.ITEM_SPEED\r\n\t\tself.contain = contain\r\n\t\tself.life = life\r\n\t\tself.rate = rate\r\n\t\tself.last_time = last_time\r\n\t\tself.usage = usage # 是否主动使用\r\n\t\tself.name = name\r\n\r\n\r\nclass Item(object):\r\n\r\n\tdef __init__(self, item_type):\r\n\t\tself.item_type = item_type\r\n\t\tself.life = self.item_type.life\r\n\t\tself.status = const.ITEM_STATUS_CREATE\r\n\t\tself.in_brick = False\r\n\t\tself.index = 0\r\n\t\t# 初始化位置\r\n\t\tposx = random.randint(1, const.GRID_NUM_X - 2)\r\n\t\tself.gridpos = (posx, 0)\r\n\t\tif posx == 1:\r\n\t\t\tposx = const.GRID_SIZE * 3 / 2\r\n\t\telse:\r\n\t\t\tposx = const.GRID_SIZE * posx + const.GRID_SIZE / 2\r\n\t\tself.pos = (posx, 0)\r\n\r\n\t# 获得道具处理自己,后续操作期待中。。。\r\n\tdef on_eaten(self):\r\n\t\tself.status = const.ITEM_STATUS_KILL\r\n\r\n\t# 先无视...\r\n\tdef on_brick_eaten(self):\r\n\t\tpass\r\n\r\n# 道具管理器\r\nclass ItemManager(object):\r\n\r\n\tdef __init__(self):\r\n\t\tself._items_prototype = {}\r\n\t\tself.rate_sum = 0 # 全部类型的概率饼图总值\r\n\t\tself.rate_in_brick = const.ITEM_IN_BRICK_RATE\r\n\r\n\t# 初始化道具类型\r\n\tdef init_item_types(self):\r\n\t\tprototypes = self._items_prototype\r\n\r\n\t\tprototypes[const.ITEM_TYPE_FIRE_BALL] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_FIRE_BALL, const.ITEM_RATE_BALL_TYPE, usage=True)\r\n\t\tprototypes[const.ITEM_TYPE_ICE_BALL] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ICE_BALL,const. ITEM_RATE_BALL_TYPE, usage=True)\r\n\t\tprototypes[const.ITEM_TYPE_THUNDER_BALL] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_THUNDER_BALL, const.ITEM_RATE_BALL_TYPE, usage=True)\r\n\r\n\t\t# 加bar生命的物品\r\n\t\tprototypes[const.ITEM_TYPE_ADD_BAR_LIFE] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ADD_BAR_LIFE, 80, 150)\r\n\t\t# 减bar生命的物品\r\n\t\tprototypes[const.ITEM_TYPE_SUB_BAR_LIFE] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_SUB_BAR_LIFE, 80, -150)\r\n\t\t# 加bar能量的物品\r\n\t\tprototypes[const.ITEM_TYPE_ADD_BAR_EN] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ADD_BAR_EN, 50, 50)\r\n\r\n\t\t# 加ctrlbar的加速度的物品\r\n\t\tprototypes[const.ITEM_TYPE_ADD_BAR_ACC] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ADD_BAR_ACC, 50, last_time=10, usage=True, name='Speed Up')\r\n\t\t# 加bar长度的物品\r\n\t\tprototypes[const.ITEM_TYPE_ADD_BAR_LEN] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ADD_BAR_LEN, 150, last_time=20, usage=True, name='Longest')\r\n\t\t# 时间减慢物品\r\n\t\tprototypes[const.ITEM_TYPE_TIME_SLOW] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_TIME_SLOW, 150, last_time=5, usage=True, name='Time Slow')\r\n\t\t# 威力加强\r\n\t\tprototypes[const.ITEM_TYPE_ADD_DAMAGE] = \\\r\n\t\t\t\tItemType(const.ITEM_TYPE_ADD_DAMAGE, 100, last_time=5, usage=True, name='Damage Up')\r\n\r\n\t\t# #\r\n\t\tfor index in prototypes:\r\n\t\t\tself.rate_sum += prototypes[index].rate\r\n\r\n\tdef init_items(self):\r\n\t\tself.interval = const.ITEM_INTERVAL\r\n\t\tself.create_time = self.interval\r\n\t\tself.itemdict = {}\r\n\t\tself.itemnum = 0\r\n\t\tself.cur_id = 1\r\n\t\tself.level = 1\r\n\r\n\tdef get_item_type(self, id):\r\n\t\tassert id in self._items_prototype\r\n\t\treturn self._items_prototype[id]\r\n\r\n\t# 产生新道具\r\n\tdef create_item(self, type_id):\r\n\t\tif type_id == 0:\r\n\t\t\treturn None\r\n\t\tassert(type_id in self._items_prototype)\r\n\t\titem = Item(self._items_prototype[type_id])\r\n\t\treturn item\r\n\r\n\t# 道具落到砖头里面\r\n\tdef on_hit_brick(self, brick, item):\r\n\t\titem.pos = (item.pos[0], item.gridpos[1] * const.GRID_SIZE + const.GRID_SIZE / 2)\r\n\t\tin_rate = random.randint(1, 100)\r\n\t\tif in_rate <= self.rate_in_brick:\r\n\t\t\titem.status = const.ITEM_STATUS_IN_BRICK\r\n\t\t\tbrick.has_item = True\r\n\t\telse:\r\n\t\t\tif item.gridpos[1] < 14:\r\n\t\t\t\titem.gridpos = (item.gridpos[0], item.gridpos[1] + 1)\r\n\t\t\telse:\r\n\t\t\t\titem.gridpos = (item,gridpos[0], 14)\r\n\r\n\t# 道具跟随下压效果\r\n\tdef on_add_line(self):\r\n\t\tfor index in self.itemdict:\r\n\t\t\titem = self.itemdict[index]\r\n\t\t\tif item.status == const.ITEM_STATUS_IN_BRICK:\r\n\t\t\t\titem.gridpos = (item.gridpos[0], item.gridpos[1] + 1)\r\n\t\t\t\titem.pos = (item.pos[0], item.gridpos[1] * const.GRID_SIZE + const.GRID_SIZE / 2)\r\n\r\n\t# 道具消失\r\n\tdef on_kill(self, index):\r\n\t\tself.itemnum -= 1\r\n\t\tdel self.itemdict[index]\r\n\r\n\t# 道具碰到球, 先无视掉\r\n\tdef on_hitball(self):\r\n\t\tpass\r\n\r\n\t# 道具下落\r\n\tdef drop_item_at(self, index_x, index_y):\r\n\t\tfor index in self.itemdict:\r\n\t\t\titem = self.itemdict[index]\r\n\t\t\tif item.gridpos == (index_x, index_y) and item.status == const.ITEM_STATUS_IN_BRICK:\r\n\t\t\t\titem.status = const.ITEM_STATUS_ACTIVE\r\n\t\t\t\treturn index\r\n\r\n\t# 根据几率生成新道具\r\n\tdef new_item(self):\r\n\t\t# 产生一个小于self.rate_sum的随机数\r\n\t\t# 根据随机数减去各种物品中的rate来确定产生哪种物品\r\n\t\tid = random.randint(1, self.rate_sum)\r\n\t\titem = None\r\n\t\tfor index in self._items_prototype:\r\n\t\t\ttype = self._items_prototype[index]\r\n\t\t\tid -= type.rate\r\n\t\t\tif id <= 0:\r\n\t\t\t\titem = self.create_item(type.type)\r\n\t\t\t\tbreak\r\n\r\n\t\tif item == None:\r\n\t\t\treturn None\r\n\t\titem.status = const.ITEM_STATUS_ACTIVE\r\n\t\titem.index = self.cur_id\r\n\t\tself.itemdict[self.cur_id] = item\r\n\t\tself.cur_id += 1\r\n\t\tself.itemnum += 1\r\n\r\n\t\treturn self.cur_id - 1\r\n\r\n\t# 道具管理相应更新\r\n\tdef update(self, level, brickgrids, bottombar, ball, time):\r\n\t\tcreatenew = [] # 新增加的物品\r\n\t\tdrop_item = [] # 掉落出去的物品\r\n\t\teaten_item = [] # 被吃掉的物品\r\n\t\tif self.level != level:\r\n\t\t\tself.rate_in_brick = const.ITEM_IN_BRICK_RATE + level * const.ITEM_IN_RATE_FACTOR\r\n\t\tif self.create_time <= 0:\r\n\t\t\tself.create_time = self.interval\r\n\t\t\t# 是时候产生物品了\r\n\t\t\tif self.itemnum < const.ITEM_MAX_NUM:\r\n\t\t\t\tid = self.new_item()\r\n\t\t\t\tif id:\r\n\t\t\t\t\tcreatenew.append(id)\r\n\t\telse:\r\n\t\t\tself.create_time -= time\r\n\t\t# update物品信息\r\n\t\tfor index in self.itemdict.keys():\r\n\t\t\titem = self.itemdict[index]\r\n\t\t\tif item.status == const.ITEM_STATUS_ACTIVE:\r\n\t\t\t\t# 下一个位置\r\n\t\t\t\tnextposy = item.pos[1] + item.item_type.speed * time\r\n\t\t\t\t# 检测是否到了该grid中心,到了就找是否有砖块\r\n\t\t\t\tif nextposy >= item.gridpos[1] * const.GRID_SIZE + const.GRID_SIZE / 2:\r\n\t\t\t\t\tbrick = brickgrids[item.gridpos[1]][item.gridpos[0]]\r\n\t\t\t\t\tif brick and brick.has_item == False and brick.status != const.BRICK_IGNORE:\r\n\t\t\t\t\t\tself.on_hit_brick(brick, item)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\titem.gridpos = (item.gridpos[0], item.gridpos[1] + 1)\r\n\t\t\t\telse:\r\n\t\t\t\t\titem.pos = (item.pos[0], nextposy)\r\n\t\t\t\t# 检测是否被吃掉\r\n\t\t\t\tif nextposy >= bottombar.pos[1]:\r\n\t\t\t\t\tif item.pos[0] >= bottombar.pos[0] - bottombar.width / 2 \\\r\n\t\t\t\t\t\tand item.pos[0] <= bottombar.pos[0] + bottombar.width /2:\r\n\t\t\t\t\t\t\titem.pos = (item.pos[0], bottombar.pos[1])\r\n\t\t\t\t\t\t\tbottombar.on_eate(item)\r\n\t\t\t\t\t\t\titem.on_eaten()\r\n\t\t\t\t\t\t\t# 加入被吃了更新列表\r\n\t\t\t\t\t\t\teaten_item.append(index)\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\titem.gridpos = (item.gridpos[0], 14)\r\n\t\t\t\t\t\titem.status = const.ITEM_STATUS_KILL\r\n\t\t\t\t\t\tdrop_item.append(index)\r\n\t\t\t\t\t\tcontinue\r\n\t\t\tif item.status == const.ITEM_STATUS_KILL:\r\n\t\t\t\tself.on_kill(index)\r\n\t\t\tif item.status == const.ITEM_STATUS_IN_BRICK:\r\n\t\t\t\tcontinue\r\n\t\treturn createnew, drop_item, eaten_item\r\n\r\n","sub_path":"logic/itemmanager.py","file_name":"itemmanager.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"472013852","text":"\"\"\"\n=========================\nMunich Adjustment Example\n=========================\n\nThis example demonstrates how to adjust LDFs by the relationship between Paid\nand Incurred using the MunichAdjustment.\n.\n\"\"\"\n\nimport chainladder as cl\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_style('whitegrid')\nsns.set_palette('muted')\n\n# Load data\nmcl = cl.load_dataset('mcl')\n# Volume weighted (default) LDFs\ndev = cl.Development().fit_transform(mcl)\n# Traditional Chainladder\ncl_traditional = cl.Chainladder().fit(dev)\n# Munich Adjustment\ndev_munich = cl.MunichAdjustment(paid_to_incurred={'paid':'incurred'}).fit_transform(dev)\ncl_munich = cl.Chainladder().fit(dev_munich)\n\n# Plot data\nfig, (ax, ax2) = plt.subplots(ncols=2, sharex=True, figsize=(10,5))\nplot1_data = cl_munich.ultimate_['paid'].to_frame()\nplot1_data.columns = ['Paid Ultimate']\nplot1_data['Incurred Ultimate'] = cl_munich.ultimate_['incurred'].to_frame()\nplot2_data = (cl_munich.ultimate_['paid']/cl_munich.ultimate_['incurred']).to_frame()\nplot2_data.columns = ['Munich']\nplot2_data['Traditional'] = (cl_traditional.ultimate_['paid']/cl_traditional.ultimate_['incurred']).to_frame()\nplot1_data.plot(kind='bar', ax=ax)\nax.set_ylabel('Ultimate')\nax.set_xlabel('Accident Year')\nax.set_title('Munich Chainladder')\nplot2_data.plot(kind='bar', ax=ax2, ylim=(0,1.25))\nax2.set_title('P/I Ratio Comparison')\nax2.set_xlabel('Accident Year')\ng = plt.ylabel('Paid Ultimate / Incurred Ultimate')\n","sub_path":"examples/plot_munich.py","file_name":"plot_munich.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"32311219","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 11 2n:47:05 2018\n\n@author: zakaria\n\"\"\"\nimport time\nimport math\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter import messagebox\nimport pycosat\nfrom pprint import pprint\n#### Bagian GUI ############\ndef SolveOptionPressed():\n menu.entryconfig(\"Solve\",state=DISABLED)\n Solve(sudoku)\n global index\n #pprint(solusi)\n #print(len(solusi))\n if(jumSol==0):\n msgatbottom.configure(text=\"Solusi 0/0.\")\n messagebox.showinfo(\"Gagal!\", \"Sudoku Tidak Memiliki Solusi\")\n menu.entryconfig(\"Solve\",state=NORMAL)\n elif(jumSol==1):\n msgatbottom.configure(text=\"Solusi 1/1.\")\n messagebox.showinfo(\"Berhasil!\", \"Sudoku Solved\")\n else:\n msgatbottom.configure(text=\"Solusi \"+str(index)+\"/\"+str(jumSol)+\".\")\n messagebox.showinfo(\"Berhasil!\", \"Sudoku Solved\")\n\n index +=1\n menu.entryconfig(\"Next\",state=NORMAL)\ndef Next():\n menu.entryconfig(\"Prev\",state=NORMAL)\n global index\n UpdateBoard(solusi,index)\n msgatbottom.configure(text=\"Solusi \"+str(index)+\"/\"+str(jumSol)+\".\")\n index +=1\n if(index == jumSol+1):\n menu.entryconfig(\"Next\",state=DISABLED)\n\ndef PrebaseN():\n menu.entryconfig(\"Next\",state=NORMAL)\n global index\n UpdateBoard(solusi,index-2)\n msgatbottom.configure(text=\"Solusi \"+str(index-2)+\"/\"+str(jumSol)+\".\")\n index -=1\n if(index == 2):\n menu.entryconfig(\"Prev\",state=DISABLED)\n\n\ndef LoadFile():\n global endflag, origsudoku\n global solusi\n global given\n global index\n index = 1\n given=N*N\n solusi =[]\n filename=askopenfilename()\n sudoku=LoadCSVtoArray(filename)\n endflag=False\n UpdateBoard(sudoku,0)\n menu.entryconfig(\"Next\",state=DISABLED)\n menu.entryconfig(\"Prev\",state=DISABLED)\n menu.entryconfig(\"Solve\",state=NORMAL)\n msgatbottom.configure(text=\"Sudoku siap. \"+str(given)+\" Givens\")\n\ndef Sudoku4():\n filemenu.entryconfig(\"Sud4x4\",state=DISABLED)\n filemenu.entryconfig(\"Sud9x9\",state=NORMAL)\n filemenu.entryconfig(\"Sud16x16\",state=NORMAL)\n menu.entryconfig(\"Solve\",state=DISABLED)\n menu.entryconfig(\"Next\",state=DISABLED)\n menu.entryconfig(\"Prev\",state=DISABLED)\n global n,N,N1,orig_sudoku,sudoku,cell\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j].grid_forget()\n n=2\n N1=5\n N=4\n sudoku = [[0 for x in range(N)] for x in range(N)]\n orig_sudoku = [[0 for x in range(N)] for x in range(N)]\n cell = [[1 for x in range(N1)] for x in range(N1)]\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j] = Label(frame, width=6, font=\"bold\", height=3, relief=\"sunken\")\n cell[i][j].grid(row=i,column=j, padx=3, pady=2)\n cell[i][j].configure(bg=GridColor(i,j))\n msgatbottom.configure(text=\"Masukkan Sudoku\")\n\ndef Sudoku9():\n filemenu.entryconfig(\"Sud4x4\",state=NORMAL)\n filemenu.entryconfig(\"Sud9x9\",state=DISABLED)\n filemenu.entryconfig(\"Sud16x16\",state=NORMAL)\n menu.entryconfig(\"Solve\",state=DISABLED)\n menu.entryconfig(\"Next\",state=DISABLED)\n menu.entryconfig(\"Prev\",state=DISABLED)\n global n,N,N1,orig_sudoku,sudoku,cell\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j].grid_forget()\n n=3\n N1=10\n N=9\n sudoku = [[0 for x in range(N)] for x in range(N)]\n orig_sudoku = [[0 for x in range(N)] for x in range(N)]\n cell = [[1 for x in range(N1)] for x in range(N1)]\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j] = Label(frame, width=6, font=\"bold\", height=3, relief=\"sunken\")\n cell[i][j].grid(row=i,column=j, padx=3, pady=2)\n cell[i][j].configure(bg=GridColor(i,j))\n msgatbottom.configure(text=\"Masukkan Sudoku\")\n\ndef Sudoku16():\n filemenu.entryconfig(\"Sud4x4\",state=NORMAL)\n filemenu.entryconfig(\"Sud9x9\",state=NORMAL)\n filemenu.entryconfig(\"Sud16x16\",state=DISABLED)\n menu.entryconfig(\"Solve\",state=DISABLED)\n menu.entryconfig(\"Next\",state=DISABLED)\n menu.entryconfig(\"Prev\",state=DISABLED)\n global n,N,N1,orig_sudoku,sudoku,cell\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j].grid_forget()\n n=4\n N1=17\n N=16\n sudoku = [[0 for x in range(N)] for x in range(N)]\n orig_sudoku = [[0 for x in range(N)] for x in range(N)]\n cell = [[1 for x in range(N1)] for x in range(N1)]\n for i in range(1,N1):\n for j in range(1,N1):\n cell[i][j] = Label(frame, width=2, font=\"bold\", height=1, relief=\"sunken\")\n cell[i][j].grid(row=i,column=j, padx=1, pady=1)\n cell[i][j].configure(bg=GridColor(i,j))\n msgatbottom.configure(text=\"Masukkan Sudoku\")\n\ndef LoadCSVtoArray(filename):\n import csv\n with open(filename) as f:\n reader = csv.reader(f)\n i=0\n for row in reader:\n sudoku[i]=row\n #del sudoku[i][-1]\n i=i+1\n for i in range(0,N):\n for j in range(0,N):\n a=sudoku[i][j]\n if(len(a)==0):\n sudoku[i][j]=orig_sudoku[i][j]=0\n elif(a=='n'):\n sudoku[i][j]=orig_sudoku[i][j]=pop(sudoku[i][j])\n else:\n sudoku[i][j]=orig_sudoku[i][j]=int(sudoku[i][j])\n #print(sudoku)\n return sudoku\n\ndef About():\n txt=\"Masukkan sudoku dengan menekan 'File' pada menu lalu menekan 'Load'. Sudoku harus disimpan dengan format CSV. Tekan 'Solve' untuk memecahkan sudoku. Jika sudoku memiliki lebih dari satu solusi tekan 'Next' untuk melihat solusi lainnya. Tekan'Prev' untuk melihat solusi sebelumnya\"\n messagebox.showinfo(\"Help\", txt)\n\ndef UpdateBoard(board,n):\n global given\n if(n<1):\n for i in range(0,N):\n for j in range(0,N):\n a=board[i][j]\n if a==0:\n given -=1\n cell[i+1][j+1].configure(text=\"\")\n else:\n if (orig_sudoku[i][j]==0):\n txtcolor=\"red\"\n else:\n txtcolor=\"black\"\n cell[i+1][j+1].configure(text=a, fg=txtcolor)\n else:\n for i in range(0,N):\n for j in range(0,N):\n a=board[n-1][i][j]\n if a==0:\n cell[i+1][j+1].configure(text=\"\")\n else:\n if (orig_sudoku[i][j]==0):\n txtcolor=\"red\"\n else:\n txtcolor=\"black\"\n cell[i+1][j+1].configure(text=a, fg=txtcolor)\n\n\n\ndef GridColor(i,j):\n if n%2==1:\n z=(n*int((i-1)/n))+1 + int((j-1)/n)\n else:\n z=(int((i-1)/n))+1 + int((j-1)/n)\n if z%2==0:\n z=\"ghostwhite\"\n else:\n z=\"yellow\"\n return z\n\n\n\n########## Bagian Sudoku Solver ##########\n\n\ndef ShowBoard(s):\n global solusi\n solusi.append([])\n for x in range(0,N):\n solusi[jumSol-1].append([])\n #print()\n for y in range(0,N):\n solusi[jumSol-1][x].append(s[x][y])\n #print(s[x][y],end=\"\")\n #print()\n\ndef baseN(i, j, v):\n return N*N* (i - 1) + N * (j - 1) + v\n\n#merubah sudoku menjadi DIMACS\ndef sudoku_clauses():\n res = []\n\n #Setidaknya ada satu angka di setiap entri:\n\n for r in range(1, N1):\n for c in range(1, N1):\n l=[]\n for v in range(1, N1):\n l.append(baseN(r,c,v))\n res.append(l)\n\n #Setiap angka muncul paling banyak satu kali di setiap baris:\n\n for r in range(1, N1):\n for v in range(1, N1):\n for c in range(1, N):\n for i in range(c+1,N1):\n res.append([-baseN(r, c, v), -baseN(r, i, v)])\n\n #Setiap angka muncul paling banyak satu kali di setiap kolom:\n for c in range(1, N1):\n for v in range(1, N1):\n for r in range(1, N):\n for i in range(r+1,N1):\n res.append([-baseN(r, c, v), -baseN(i, c, v)])\n\n #Setiap angka muncul paling banyak sekali dalam setiap sub-grid n x n:\n #blok1=0\n for v in range(1, N1):\n for i in range(n):\n for j in range(n):\n for c in range(1, n+1):\n for r in range(1, n):\n for k in range(r + 1, n+1):\n for l in range(1,n+1):\n #blok1+=1\n #print([-((n*i+r)*100+ (n*j+c)*10+d), -((n*i+k)*100+(n*j+l)*10+d)])\n res.append([-baseN((n*i+r), (n*j+c), v), -baseN((n*i+k), (n*j+l), v)])\n\n #print(blok1)\n\n return res\n\n########################### memecahkan sudoku\ndef Solve(sudoku):\n #waktu CPU mulai\n start = time.time()\n clauses = sudoku_clauses()\n for i in range(1, N1):\n for j in range(1, N1):\n d = sudoku[i - 1][j - 1]\n # untuk setiap given.\n if d:\n clauses.append([baseN(i, j, d)])\n\n def read_cell(i, j):\n # mengembalikan i,j\n for d in range(1, N1):\n if baseN(i, j, d) in sol:\n return d\n # memulai SAT solver\n #print(len(clauses))\n #pprint(clauses)\n sol = set(pycosat.solve(clauses))\n #print(sol)\n checker=len(sol)\n counter=0\n global solusi\n global jumSol\n sudokuSol=[]\n if checker == 5:\n #print('Sudoku tidak memiliki solusi')\n jumSol=counter\n while (checker != 5):\n if(counter==100):\n return\n counter+=1\n jumSol=counter\n #print(counter)\n #print(sol)\n #sol = pycosat.solve(cnf)\n\n for i in range(1, N1):\n for j in range(1, N1):\n sudoku[i - 1][j - 1] = read_cell(i, j)\n\n #print('Answer: '+str(counter))\n #print(numclause)\n ShowBoard(sudoku)\n #print(len(sol))\n #print()\n sudokuSol.append(sudoku)\n clauses.append([-x for x in sol])\n sol = set(pycosat.solve(clauses))\n checker=len(sol)\n #print(sudokuSol[0])\n end = time.time()\n print(\"Time: \"+str(end - start))\n if(counter<2):\n UpdateBoard(sudoku,0)\n else:\n UpdateBoard(solusi,1)\n\n\n\n############## Main #########################\nN=16\nn=int(math.sqrt(N))\nN1=N+1\nsudoku = [[0 for x in range(N)] for x in range(N)]\norig_sudoku = [[0 for x in range(N)] for x in range(N)]\ncell = [[1 for x in range(N1)] for x in range(N1)]\nsolusi = []\ngiven = 0\njumSol = 0\nindex = 1\nendflag=False\nroot = Tk()\nroot.title(\"Sudoku Solver\")\n\nmenu = Menu(root)\nroot.config(menu=menu)\nfilemenu = Menu(menu)\nmenu.add_cascade(label=\"File\", menu=filemenu)\n\nactionmenu= Menu(menu)\nmenu.add_command(label=\"Solve\", state=DISABLED, command=SolveOptionPressed)\n\nhelpmenu = Menu(menu)\nmenu.add_cascade(label=\"Help\", menu=helpmenu)\n\nactionmenu= Menu(menu)\nmenu.add_command(label=\"Prev\", state=DISABLED, command=Prev)\n\nactionmenu= Menu(menu)\nmenu.add_command(label=\"Next\", state=DISABLED, command=Next)\n\n\nfilemenu.add_command(label=\"Load\", command=LoadFile)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Sud4x4\", command=Sudoku4)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Sud9x9\", command=Sudoku9)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Sud16x16\", state=DISABLED, command=Sudoku16)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Exit\", command=root.quit)\n\nhelpmenu.add_command(label=\"About...\", command=About)\n\nframe=Frame(root)\nframe.grid(ipady=1,ipadx=1)\n\nfor i in range(1,N1):\n for j in range(1,N1):\n cell[i][j] = Label(frame, width=2, font=\"bold\", height=1, relief=\"sunken\")\n cell[i][j].grid(row=i,column=j, padx=1, pady=1)\n cell[i][j].configure(bg=GridColor(i,j))\nmsgatbottom=Label(frame,height=1)\nmsgatbottom.grid(row=N1,column=1,columnspan=N,sticky=\"we\")\nmsgatbottom.configure(text=\"Masukkan Sudoku\")\nmainloop()\n","sub_path":"sudokuSolver.py","file_name":"sudokuSolver.py","file_ext":"py","file_size_in_byte":11742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"136383156","text":"# region IMPORTS \nimport os\n\nimport yaml\nimport operator\nimport time\nfrom datetime import date, datetime, timedelta\n\nimport pytz\nfrom dateutil.relativedelta import relativedelta\n\nfrom functools import reduce\nfrom peewee import *\n# endregion\n\n# region Logger\nimport logging\nfrom debug import setup_logging\n\nlog = logger = logging.getLogger(\"dbo\")\nsetup_logging()\n# endregion\n\n\n# region GLOBALS \nrealpath = os.path.dirname(os.path.realpath(__file__))\nrp = realpath\n\ndb_path = os.path.join(realpath, 'database.db')\ndb = SqliteDatabase(db_path)\n# endregion\n\n# region FUNCTIONS \ndef read_yaml(filename):\n with open(os.path.join(filename), \"r\", encoding=\"utf-8\") as f:\n data = yaml.safe_load(f)\n return data\n\ndef read_config_data():\n return read_yaml(\"config\")\n\ndef read_config(filename):\n data = read_yaml(os.path.join(realpath, 'config', filename + '.yaml'))\n return data\n\ndef write_config(filename, data):\n with open(os.path.join(realpath, 'config', filename + '.yaml'), \"w+\", encoding=\"utf-8\") as f:\n f.write(yaml.dump(data, default_flow_style=False))\n\n\ndef config(*args):\n conf = read_config('config')\n return reduce(operator.getitem, args, conf)\n\ndef set_config(*args, value=None):\n conf = read_config('config')\n config(conf, args[:-1])[args[-1]] = value\n write_config('config', conf)\n\n\n# endregion\n\n\n\nclass Accounting(Model):\n address = CharField()\n date = DateTimeField()\n upload = IntegerField()\n download = IntegerField()\n\n class Meta:\n database = db\n\nclass MontlyArchive(Model):\n address = CharField()\n date = DateField()\n upload = IntegerField()\n download = IntegerField()\n\n class Meta:\n database = db\n\ndef trunc_datetime(someDate):\n return someDate.replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n\ndef compare_months(A, B):\n A = trunc_datetime(A)\n B = trunc_datetime(B)\n return A == B\n\ndef cleanup_database():\n '''\n Remove oldest entries, count their sum and record into MonthlyArchive DB.\n '''\n try:\n now = datetime.utcnow().date()\n data = {}\n query = Accounting.select()\n for entry in query:\n entry_date = entry.date.date()\n if entry_date < now - relativedelta(months=config(\"general\", \"keep_months\")):\n if entry_date not in data:\n data[entry_date] = [entry.date, entry.address, entry.download, entry.upload]\n else:\n data[entry_date][1] = entry.download + data[entry_date][1]\n data[entry_date][2] = entry.upload + data[entry_date][2]\n entry.delete_instance()\n for dt, data in sorted(data.items()):\n MontlyArchive.create(\n date = dt,\n address = data[0],\n download = data[1],\n upload = data[2]\n )\n except Exception as e:\n log.error(\"Database cleanup failed.\", exc_info=True)\n\ndef cleanup_database_loop():\n while True:\n cleanup_database()\n # TODO Replace with proper scheduler\n time.sleep(21600) # 21600 second = 6 hours\n\nlog.info(\" \".join([\"Using DB\", str(db), \"At path:\", str(db_path)]))\n\ndb.connect()\ndb.create_tables([Accounting])\n\n","sub_path":"dbo.py","file_name":"dbo.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"149214278","text":"# -*- coding: utf-8 -*-\n\nclass DefineContainer:\n def __init__(self):\n \"\"\"\n dictionary\n +-- Comiket (unicode)\n | +-- number (unicode) data:(int)\n | +-- name (unicode) data:(unicode)\n |\n +-- cutInfo (unicode)\n | +-- width (unicode) data:(int)\n | +-- height (unicode) data:(int)\n | +-- origin_x (unicode) data:(int)\n | +-- origin_y (unicode) data:(int)\n | +-- offset_x (unicode) data:(int)\n | +-- offset_y (unicode) data:(int)\n |\n +-- mapTableInfo (unicode)\n | +-- width (unicode) data:(int)\n | +-- height (unicode) data:(int)\n | +-- origin_x (unicode) data:(int)\n | +-- origin_y (unicode) data:(int)\n |\n +-- ComiketDate (unicode)\n | +-- 20XXXXXX (開催日付)(int)\n | | +-- year (unicode) data:(int)\n | | +-- month (unicode) data:(int)\n | | +-- day (unicode) data:(int)\n | | +-- week (unicode) data:(unicode)\n | | +-- page (unicode) data:(int)\n | +-- 20XXXXXX\n | :\n |\n +-- ComiketMap\n | +-- 東123 (地図名)(unicode)\n | | +-- name (unicode) data:(unicode)\n | | +-- map_key (unicode) data:(unicode)\n | | +-- print_area (unicode) data:(int[X,X,X,X])\n | | +-- small_map_key (unicode) data:(unicode)\n | | +-- fine_print_area (unicode) data:(int[X,X,X,X])\n | | +-- reverse (unicode) data:(bool)\n | +-- 東456\n | :\n |\n +-- ComiketArea\n | +-- 東123壁 (地区名)(unicode)\n | | +-- name (unicode) data:(unicode)\n | | +-- map (unicode) data:(unicode)\n | | +-- block (unicode) data:(unicode)\n | | +-- print_area unicode) data:(int[X,X,X,X])\n | | +-- small_map_key (key=東123壁,東456壁,西1壁,西2壁を除く)(unicode) data:(unicode)\n | | +-- fine_print_area (key=東123壁,東456壁,西1壁,西2壁を除く)(unicode) data:(int[X,X,X,X])\n | +-- 東1\n | :\n |\n +-- ComiketGenre (unicode)\n +-- 100 (key=ジャンルコード(int) value=ジャンル名(unicode))\n +-- 110\n :\n \"\"\"\n\n self.comiket_number = None\n self.comiket_name = None\n self.cut_info = DefineContainer.CutInfoContainer()\n self.map_table_info = DefineContainer.MapTableInfoContainer()\n self.comiket_date = {}\n self.comiket_map = {}\n self.comiket_area = {}\n self.comiket_genre = {}\n\n class CutInfoContainer:\n def __init__(self):\n self.width = None\n self.height = None\n self.origin_x = None\n self.origin_y = None\n self.offset_x = None\n self.offset_y = None\n\n class MapTableInfoContainer:\n def __init__(self):\n self.width = None\n self.height = None\n self.origin_x = None\n self.origin_y = None\n\n class ComiketDateContainer:\n def __init__(self):\n self.year = None\n self.month = None\n self.day = None\n self.week = None\n self.page = None\n\n class ComiketMapContainer:\n def __init__(self):\n self.name = None\n self.map_key = None\n self.print_area = None\n self.small_map_key = None\n self.fine_print_area = None\n self.reverse = None\n\n class ComiketAreaContainer:\n def __init__(self):\n self.name = None\n self.map = None\n self.block = None\n self.print_area = None\n self.small_map_key = None\n self.fine_print_area = None\n\nif __name__ == \"__main__\":\n pass","sub_path":"src/container/define.py","file_name":"define.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"125102992","text":"import csv;\nimport math;\nimport random;\nfrom timeit import Timer;\n\n#从csv文件中读取数据,并转换为float\ndef load_cdv(filename):\n data = csv.reader(open(filename,'r'))\n dataset = list(data)\n for i in range(len(dataset)):\n dataset[i] = [float(x) for x in dataset[i]]\n return dataset\n\n#将dataset按 radio:(1-radio) 的比例分成训练数据和测试数据两部分\ndef split_dataset(dataset,radio):\n train_data = dataset\n test_data = []\n test_size = int(len(dataset)*(1-radio))\n while len(test_data) str:\n \"\"\"\n Helper function to escape telegram markup symbols.\n Args:\n text (:obj:`str`): The text.\n version (:obj:`int` | :obj:`str`): Use to specify the version of telegrams Markdown.\n Either ``1`` or ``2``. Defaults to ``1``.\n entity_type (:obj:`str`, optional): For the entity types ``PRE``, ``CODE`` and the link\n part of ``TEXT_LINKS``, only certain characters need to be escaped in ``MarkdownV2``.\n See the official API documentation for details. Only valid in combination with\n ``version=2``, will be ignored else.\n \"\"\"\n if int(version) == 1:\n escape_chars = r\"_*`[\"\n elif int(version) == 2:\n if entity_type in [\"pre\", \"code\"]:\n escape_chars = r\"\\`\"\n elif entity_type == \"text_link\":\n escape_chars = r\"\\)\"\n else:\n escape_chars = r\"_*[]()~`>#+-=|{}.!\"\n else:\n raise ValueError(\"Markdown version must be either 1 or 2!\")\n\n return re.sub(f\"([{re.escape(escape_chars)}])\", r\"\\\\\\1\", text)\n\n\ndef get_user_link(user_id: Text, mention_text: Text):\n return f\"[{mention_text}](tg://user?id={user_id})\"\n","sub_path":"dataset/actions/utils/markdown.py","file_name":"markdown.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"23701038","text":"import markdown\n\nimport sys,os\n\npath = sys.argv[1]\nwrite_target = sys.argv[2]\n\ndef make_html(s, filename):\n template = open(\"html_template.html\", encoding=\"utf-8\").read()\n spl = template.split('---bodysplit---')\n open(filename, 'w', encoding=\"utf-8\").write(spl[0]+'\\n\\n'+s+'\\n\\n'+spl[1])\n\nfor a in os.listdir(path):\n\n if a[-3:] == '.md':\n print(a)\n # htmlfile = open(write_target+\"\\\\\"+a+\".html\",'w', encoding=\"utf-8\")\n md = open(path+\"\\\\\"+a, encoding=\"utf-8\").read()\n md = md.replace(\"```text\", \"

\")\\\n            .replace(\"```rust,ignore\", \"
\")\\\n            .replace(\"```rust\", \"
\")\\\n            .replace(\"```\", \"
\")\n # htmlfile.write(html)\n html = markdown.markdown(md)\n\n make_html(html, write_target+\"\\\\\"+a+\".html\")\n\n","sub_path":"_projlab/_various/rustbook.py","file_name":"rustbook.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"524037302","text":"import sys\r\nimport os\r\nimport json\r\nimport pprint\r\nimport zlib\r\nfrom collections import defaultdict\r\nfrom settings import N_BINS, N_THREAD_BINS, OUT_DIR\r\nfrom multiprocessing import Pool\r\n\r\ndef get_bin(s, n_bins=N_THREAD_BINS):\r\n\treturn zlib.adler32(s.encode('utf-8')) % n_bins \r\n\r\ndef reshuffle_by_thread_bin(bin_idx, node_root_file, indir, outdir):\r\n\tprint(bin_idx)\r\n\twith open(node_root_file) as f:\r\n\t\tnode_to_root = json.load(f)\r\n\t\r\n\tbin_to_emails = defaultdict(dict)\r\n\r\n\twith open(os.path.join(indir, '%02d.json' % bin_idx)) as f:\r\n\t\temail_dict = json.load(f)\r\n\t\tfor key, email in email_dict.items():\r\n\t\t\tif key not in node_to_root: continue\r\n\t\t\temail['thread_root_key'], email['thread_level'] = node_to_root[key]\r\n\t\t\tbin_to_emails[get_bin(email['thread_root_key'])][key] = email \r\n\r\n\tfor thread_bin_idx, email_dict in bin_to_emails.items():\r\n\t\tprint(bin_idx, thread_bin_idx, len(email_dict))\r\n\t\toutfile = os.path.join(outdir, '%02d' % thread_bin_idx, '%02d.json' % bin_idx)\r\n\t\twith open(outfile, 'w') as f:\r\n\t\t\tjson.dump(email_dict, f)\r\n\r\nif __name__ == '__main__':\r\n\troot_indir = os.path.join(OUT_DIR, 'reduce_dedup_extracted/content')\r\n\troot_outdir = os.path.join(OUT_DIR, 'reduce_dedup_thread/content')\r\n\tfor thread_bin_idx in range(N_THREAD_BINS):\r\n\t\tprint(thread_bin_idx)\r\n\t\ttry:\r\n\t\t\tos.mkdir(os.path.join(root_outdir, '%02d' % thread_bin_idx))\r\n\t\texcept Exception as e:\r\n\t\t\tprint(e)\r\n\r\n\tnode_root_file = os.path.join(OUT_DIR, 'reduce_dedup_thread/node_to_root.json')\r\n\t\r\n\tpool = Pool(4)\r\n\tpool.starmap(reshuffle_by_thread_bin,\r\n\t\t[(bin_idx, node_root_file, root_indir, root_outdir) for bin_idx in range(N_BINS)])","sub_path":"reshuffle_by_thread_bin.py","file_name":"reshuffle_by_thread_bin.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"35578979","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndf1 = pd.read_csv('client.csv', encoding='cp949')\ndf2 = pd.read_csv('campaign_etc.csv', encoding='cp949')\ndf = pd.merge(df1, df2, on='index', how='inner')\ndf.drop(['index', 'poutcome'], axis='columns', inplace=True)\ndf.insert(5, 'housing', '')\ndf.loc[:25131, 'housing'] = 'yes'\ndf.loc[25131:, 'housing'] = 'No'\ndf.rename(columns={'y':'deposit'},inplace=True)\ndf.replace({'yes': 1, 'yes': 1, 'No': 0, 'no':0},inplace=True)\n\n# age 결측치 (12개) 중앙값으로 채우기\nage_median = df['age'].median(axis=0) # age_median = 39\ndf['age'].fillna(age_median, inplace=True)\ndf.isnull().sum() # age 결측치 0개 된 것 확인 가능\n\n# duration 결측치 (123개) 중앙값으로 채우기\nduration_median = df['duration'].median(axis=0) # duration_median = 181\ndf['duration'].fillna(duration_median, inplace=True)\ndf.isnull().sum() # duration 결측치 0개 된 것 확인 가능\n\n# balance 결측치 (16개) 제거\n## 남은 결측치가 balance 결측치뿐이라 전체에 대해 dropna 실행가능\ndf.dropna(inplace=True)\ndf.isnull().sum() # 모든 결측치 사라짐\n\n# age 는 자를 것 없음. 그대로 유지 (범위 자체가 크지 않고 최댓값이 95세로 오류값이라고 보기 어려우므로)\n\n\n# balance 이상치 처리\n# 음수값 제거\nbalance_negative = df['balance'] < 0\ndf.drop(df.loc[balance_negative].index, axis='index', inplace=True)\n\n# IQR 기준 이상치 제거 -> 너무 많이 잘려나가서 기각\n#q1, q3 = df['balance'].quantile(0.25), df['balance'].quantile(0.75)\n#iqr = q3-q1\n#condition = (df['balance'] > q1-1.5*iqr) & (df['balance'] < q3+1.5 *iqr)\n#df['balance'][condition].describe()\n\n# 50000 이상인 값 제거 : boxplot 상으로 시각적으로 판단\nbalance_outlier = df['balance'] > 50000\ndf.drop(df.loc[balance_outlier].index, axis='index', inplace=True)\n\n\n# day 이상치 처리\nday_outlier = (df['day']<0) | (df['day']>31)\ndf.drop(df.loc[day_outlier].index, axis='index', inplace=True)\n\n\n#campaign 는 유지 (25%-1.5IQR, 75%+1.5IQR 기준으로 outlier 확인 했을 때에 3234개가 outlier로 잡히고, 41949개가 남음.상대적으로 outlier 비율 적다고 생각하여 유지)\n\n\n#duration 이상치 처리\n# IQR 기준 이상치 제거\nduration_q1, duration_q3 = df['duration'].quantile(0.25), df['duration'].quantile(0.75)\nduration_iqr = duration_q3-duration_q1\ncondition = (df['duration'] > duration_q1-1.5*duration_iqr) & (df['duration'] < duration_q3+1.5 *duration_iqr)\ndf['duration'][condition].describe()\n\n\n# pdays 이상치 처리\n# 음수값 제거\npdays_negative = df['pdays'] <0\ndf.drop(df.loc[pdays_negative].index, axis='index', inplace=True)\n# 700 이상 제거 : boxplot 상에서 시각적으로 판단\npdays_outlier = df['pdays'] > 700\ndf.drop(df.loc[pdays_outlier].index, axis='index', inplace=True)\n\n\n# previous 이상치 처리\n# 혼자 동떨어져있는 250 이상 값 제거하기 : 혼자 너무 동떨어져있는데 boxplot 상에서 확인되어서 먼저 제거\nprevious_outlier = df['previous'] > 250\ndf.drop(df.loc[previous_outlier].index, axis='index', inplace=True)\n\n# 30 이상 제거: boxplot 상으로 시각적으로 판단\nprevious_outlier2 = df['previous'] > 30\ndf.drop(df.loc[previous_outlier2].index, axis='index', inplace=True)\n\ndf = df.T.drop_duplicates().T\n\n# 최종적으로 7718개의 데이터가 남았음. 이를 가지고 분석 진행하기로 함.\n\n# age 분석\ndf = df.astype({'age':float})\nage = plt.subplots(figsize=(12, 10))\nage = sns.violinplot(data=df, y='age')\nage.set_title(\"고객층의 age 분포\", size=20)\n\nage1 = plt.subplots(figsize=(12, 10))\nplt.rcParams['font.family'] = 'Malgun Gothic'\nage1 = sns.distplot(df['age'], bins=15)\nage1.set_title(\"고객층의 age 분포\", size=20)\n\n# marital 분석\nmarital = df['marital'].value_counts()\nplt.rc('font', family='Malgun Gothic')\nplt.rcParams['font.size'] = 15\nplt.pie(marital, labels=['married', 'single', 'divorced'], colors=['lightblue', 'darksalmon', 'mediumpurple']\n , autopct='%.1f%%', explode=(0.05, 0, 0.03))\nplt.legend()\nplt.show()\n\n# job 분석\njob = df['job'].value_counts()\nplt.rcParams['font.size'] = 15\nplt.pie(job, labels=['management', 'blue-collar', 'technician', 'admin', 'services', 'retired', 'student', 'self-employed', 'entrepreneur', 'unemployed', 'housemaid', 'unknown']\n , autopct='%.1f%%', explode=(0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01))\nplt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5))\nplt.show()\n\n# pdays 분석\npdays = plt.subplots(figsize=(12, 10))\npdays = df['pdays'].plot(kind='box')\npdays.set_title(\"마지막 contact 으로부터 지난 날의 수\")\ndf['pdays'].quantile(0.25), df['pdays'].quantile(0.5), df['pdays'].quantile(0.75), df['pdays'].mean()\n\n# duration 분석\nduration1 = plt.subplots(figsize=(12, 10))\nplt.rcParams['font.family'] = 'Malgun Gothic'\nduration = sns.distplot(df['duration'], bins=15)\nduration.set_title(\"duration 분포\", size=20)\n\n# age와 duration 관계\nimport numpy as np\n\nsns.set(rc = {'figure.figsize':(12,10)})\nage_duration = sns.stripplot(x='age', y='duration', hue=\"deposit\", palette=[\"green\", \"red\"], data=df, alpha=0.5)\nplt.title(\"customer's age and duration\", size=20)\nplt.xticks(rotation=45)\nplt.xticks(np.arange(0, 95, 5))\nplt.yticks(np.arange(0, 2500, 500))\nplt.legend(loc='center right')\nage_duration\n\n## deposit 성사된 데이터들만 가지고 age와 duration 관계 다시 확인\nsns.set(rc = {'figure.figsize':(12,10)})\nage_duration = sns.stripplot(x='age', y='duration',palette=[\"mediumpurple\"], data=df.loc[df['deposit']==1], alpha=0.5)\nplt.title(\"Yes deposit customer's age and duration\", size=20)\nplt.xticks(rotation=45)\nplt.xticks(np.arange(0, 95, 5))\nplt.yticks(np.arange(0, 2500, 500))\nplt.legend(loc='center right')\nage_duration\n\n# balance와 duration 의 관계\nsns.set(rc = {'figure.figsize':(12,10)})\nbalance_duration = sns.stripplot(x='balance', y='duration', hue=\"deposit\", palette=[\"lightblue\", \"salmon\"], data=df, alpha=0.5)\nplt.title(\"customer's balance and duration\", size=20)\nplt.xticks(rotation=90)\n#balance_duration.set_xticks(range(0,40000, 5000))\nplt.legend(loc='center right')\nbalance_duration\n\n# job에 따른 deposit 성사율\ndeposit_true = df['deposit'] == 1\ndeposit_false = df['deposit'] == 0\ntrue = df.loc[deposit_true]\ntrue_job_groups = true.groupby(\"job\")\ntrue_series = true_job_groups['deposit'].count() # 모든 column에서 데이터 수는 동일하기는 한데 굳이 dataframe으로 같은 값 여러개 띄울 필요 없어서 한 column 지정해서 호출한 것\nfalse = df.loc[deposit_false]\nfalse_job_groups = false.groupby(\"job\")\nfalse_series = false_job_groups['deposit'].count()\n\ndf_concat = pd.concat([true_series, false_series], axis=1)\ndf_concat.columns = ['true', 'false']\ndf_concat['ratio'] = df_concat['true']/(df_concat['true']+df_concat['false'])\n\nplt.rcParams['font.family'] = 'Malgun Gothic'\njob_concat = df_concat.plot(kind='bar', y='ratio')\njob_concat.set_title(\"직업군에 따른 적금 개설 성사 비율\")\n\n# marital에 따른 deposit 성사율\ndeposit_true = df['deposit'] == 1\ndeposit_false = df['deposit'] == 0\ntrue = df.loc[deposit_true]\ntrue_marital_groups = true.groupby(\"marital\")\ntrue_series1 = true_marital_groups['deposit'].count() # 모든 column에서 데이터 수는 동일하기는 한데 굳이 dataframe으로 같은 값 여러개 띄울 필요 없어서 한 column 지정해서 호출한 것\nfalse = df.loc[deposit_false]\nfalse_marital_groups = false.groupby(\"marital\")\nfalse_series1 = false_marital_groups['deposit'].count()\n\ndf_concat = pd.concat([true_series1, false_series1], axis=1)\ndf_concat.columns = ['true', 'false']\ndf_concat['ratio'] = df_concat['true']/(df_concat['true']+df_concat['false'])\n\nplt.rcParams['font.family'] = 'Malgun Gothic'\nmarital_concat = df_concat.plot(kind='bar', y='ratio', color='salmon')\nmarital_concat.set_title(\"결혼 상태에 따른 적금 개설 성사 비율\")\n\n# 그 외 요소들의 상관계수 확인\ndf= df.astype({'default':'int','loan':'int','day':'int','campaign':'int','pdays':'int','previous':'int','deposit':'int','housing':'int', 'age':'float', 'balance':'float','duration':'float'})\nsns.heatmap(df.corr(), annot=True)\n\n# 상관관계 clustermap으로 확인\ncorr = df.corr()\nsns.clustermap(corr)\n\n# deposit 과의 상관계수 내림차순 정렬\ndf.corr()['deposit'].sort_values(ascending=False)","sub_path":"codeit/final_project_analysis.py","file_name":"final_project_analysis.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"286838214","text":"#!/usr/bin/env python\nimport time\nimport math\nfrom nav_msgs.msg import OccupancyGrid # Global map \nfrom geometry_msgs.msg import PoseArray, PoseStamped, Pose2D, Pose, Twist # Global path \nimport rospy \nimport sys \nfrom visualization_msgs.msg import Marker, MarkerArray # Debug drawing \nimport tf2_ros \nfrom tf import transformations\n\n#----- Load paramters -----# \n# foot_print = [[-0.57, 0.36],[0.57, 0.36],[0.57, -0.36],[-0.57, -0.36]]\np1 = 1 # V, p controller # How much you care about 'r'\np2 = 1/0.375 # W, p controller # How much you care about 'alpha'\n# p3 = # How much you care about 'beta'\nVel_limit = 0.7 # Should be in class, modified dynamic.\nIS_ENABLE_MOVE_BACKWORD = True \n\nMAX_LINEAR_DEC = 0.7 # m/s^2\nMAX_ANGULAR_DEC = 0.7 # rad/s^2\nSAFTY_DISTANCE = 0.1 # m \nSAFTY_ANGLE = 0.05\n\n\nTOUCH_ZONE_RADIUS = 0.05 # m \nTOUCH_ZONE_ANGLE = 0.017 # rad \nADJUST_ZONE_RADIUS = 0.20 # m \n\n# LVP = LINEAR_VELOCITY_PLANNER()\npub_marker = rospy.Publisher('markers', MarkerArray,queue_size = 1, latch=False )\n\nclass LINEAR_VELOCITY_PLANNER():\n def __init__(self):\n #----- Current Pose ------# \n self.current_position = PoseStamped()\n # ---- Current Goal ------# \n self.goal = Pose2D() # PoseStamped()\n self.goal_mode = \"goal\"# \"waypoint\" # \n # ---- State Machine -----#\n self.state = \"stand_by\" # \"abort\", \"timeout\" , \"moving\"\n #------- #\n self.markerArray = MarkerArray()\n #----- Publisher ------# \n self.pub_cmd_vel = rospy.Publisher('/cmd_vel', Twist ,queue_size = 10, latch=False)\n self.cmd_vel = Twist()\n #----- Counting Star ------# \n self.t_start_moving = None \n # ---- Falgs -------# \n self.was_in_touch_zone = False \n\n def reset (self):\n '''\n Clean Current Task , and reset to init.\n '''\n # ---- Current Goal ------# \n self.goal = Pose2D() # PoseStamped()\n # ---- State Machine -----#\n self.state = \"stand_by\" # \"abort\", \"timeout\" , \"moving\"\n #------- #\n self.markerArray = MarkerArray()\n #----- Counting Star ------# \n self.t_start_moving = None \n # ---- Falgs -------# \n self.was_in_touch_zone = False \n\n def clean_screen (self):\n #------- clean screen -------#\n marker = Marker()\n marker.header.frame_id = \"/map\"\n marker.action = marker.DELETEALL\n self.markerArray.markers.append(marker)\n pub_marker.publish(self.markerArray)\n\n #------- Debug draw -------# \n self.markerArray = MarkerArray()\n\n def goal_CB(self, goal):\n rospy.loginfo (\"Target : \" + str(goal))\n\n #(self.goal.x, self.goal.y) = (goal.pose.position.x , goal.pose.position.y ) \n #self.goal.theta = transformations.euler_from_quaternion(self.pose_quaternion_2_list(goal.pose.orientation))[2]\n self.goal = goal \n self.state = \"moving\"\n # TODO Do something.\n #self.reset()\n #self.navi_goal = self.XY2idx((navi_goal.pose.position.x, navi_goal.pose.position.y))\n self.t_start_moving = time.time()\n\n \n\n def current_position_CB(self, current_position):\n self.current_position = current_position\n\n def sign (self, x):\n if x >= 0: \n return 1\n else: \n return -1 \n \n def angle_substitution(self, ang):\n '''\n Make sure ang is 0 ~ pi/2 or -0 ~ -pi/2 \n '''\n ans = (abs(ang) % (2* math.pi)) * self.sign(ang) # Make sure not ot exceed 360\n\n if ans > math.pi :\n # return (2* math.pi) - ans \n ans = ans - (2* math.pi) # Negative \n elif ans < -math.pi : \n ans = (2* math.pi) + ans # Positive \n else: \n pass \n return ans \n\n\n def iterateOnce (self):\n '''\n Switch Case \n '''\n if self.state == \"stand_by\":\n pass\n elif self.state == \"reached\":\n rospy.loginfo (\"[Linear_velocity_planner] time spend: \" + str(time.time() - self.t_start_moving))\n self.reset()\n\n elif self.state == \"moving\": \n #----- Get r , alpha , beta ------# \n # pos_dx = self.goal.pose.position.x - self.current_position.pose.position.x\n # pos_dy = self.goal.pose.position.y - self.current_position.pose.position.y\n pos_dx = self.goal.x - self.current_position.pose.position.x\n pos_dy = self.goal.y - self.current_position.pose.position.y\n r = math.sqrt(pos_dx*pos_dx + pos_dy*pos_dy)\n\n r_yaw = math.atan2(pos_dy, pos_dx)\n\n cureent_position_yaw = transformations.euler_from_quaternion(self.pose_quaternion_2_list(self.current_position.pose.orientation))[2]\n alpha = self.angle_substitution(cureent_position_yaw - r_yaw)\n\n goal_yaw = self.goal.theta # transformations.euler_from_quaternion(self.pose_quaternion_2_list(self.goal.pose.orientation))[2]\n beta = self.angle_substitution(cureent_position_yaw - goal_yaw) # cureent_position_yaw - goal_yaw \n\n # Don't make it complicate\n # theta = self.angle_substitution(goal_yaw - r_yaw) # r_yaw - goal_yaw \n\n # ------- Check Go Farword or Backword --------#\n linear_direction = 1 \n if IS_ENABLE_MOVE_BACKWORD: \n if abs(alpha) > math.pi/2:\n rospy.loginfo(\"Decide to go BackWord.\")\n cureent_position_yaw = self.angle_substitution(cureent_position_yaw + math.pi)\n alpha = self.angle_substitution(cureent_position_yaw - r_yaw)\n linear_direction = -1 \n \n if r < ADJUST_ZONE_RADIUS: \n rospy.loginfo (\"++++++++++++++++++++++++++\")\n rospy.loginfo (\"cureent_position_yaw = \" + str(cureent_position_yaw))\n rospy.loginfo (\"r_yaw = \" + str(r_yaw))\n rospy.loginfo (\"r = \" + str(r))\n rospy.loginfo (\"alpha = \" + str(alpha))\n rospy.loginfo (\"beta = \" + str(beta))\n\n # Calculate V \n V = abs(p1*r*math.cos(alpha)) * linear_direction\n\n # Calculate W \n if r < TOUCH_ZONE_RADIUS or self.was_in_touch_zone: # Inside touch zone \n self.was_in_touch_zone = True \n alpha_pecentage = 0\n beta_pecentage = 1\n # rospy.loginfo(\"+++++++++++++++++++++++++++++beta adjustment\")\n # W = -p2*beta\n '''\n elif r < ADJUST_ZONE_RADIUS : # Inside adjust zone \n if abs(theta) < math.pi/2:\n alpha_pecentage = math.pow((ADJUST_ZONE_RADIUS - r) , 2)/math.pow((ADJUST_ZONE_RADIUS - TOUCH_ZONE_RADIUS) , 2)\n beta_pecentage = 1 - (math.pow((ADJUST_ZONE_RADIUS - r) , 2)/math.pow((ADJUST_ZONE_RADIUS - TOUCH_ZONE_RADIUS) , 2))\n else: \n alpha_pecentage = 1 \n beta_pecentage = 0\n '''\n else: # Outside\n alpha_pecentage = 1 \n beta_pecentage = 0\n # W = -p2*alpha\n W = -p2 * (alpha*alpha_pecentage + beta*beta_pecentage ) # alpha_pecentage + beta_pecentage = 1 \n\n # Vel conservation\n \n if (abs(V) + abs(W)) > Vel_limit:\n k = Vel_limit / (abs(V) + abs(W))\n V = V * k\n W = W * k\n else: # Allow slower Vel\n pass \n\n #---------------------------------#\n #reached or not \n if self.goal_mode == \"waypoint\" and self.was_in_touch_zone :\n V = 0 \n W = 0\n self.state = \"reached\"\n elif self.goal_mode == \"goal\" and self.was_in_touch_zone and abs(beta) < TOUCH_ZONE_ANGLE: \n V = 0 \n W = 0\n self.state = \"reached\"\n \n #---------------------------------#\n rospy.loginfo (\"V = \" + str(V))\n rospy.loginfo (\"W = \" + str(W))\n self.cmd_vel.linear.x = V \n self.cmd_vel.angular.z = W\n self.pub_cmd_vel.publish(self.cmd_vel)\n else: \n pass \n \n def collision_calculation(self):\n pass \n #dt_linear = / + /\n #dt_angular = / + /\n\n def set_point(self, idx ,r ,g ,b ):\n '''\n Set Point at MarkArray \n '''\n marker = Marker()\n marker.header.frame_id = \"/map\"\n marker.id = idx \n marker.ns = \"tiles\"\n marker.header.stamp = rospy.get_rostime()\n marker.type = marker.SPHERE\n marker.action = marker.ADD\n marker.scale.x = 0.05\n marker.scale.y = 0.05\n marker.scale.z = 0.05\n marker.color.a = 1.0\n marker.color.r = r/255.0\n marker.color.g = g/255.0\n marker.color.b = b/255.0\n marker.pose.orientation.w = 1.0\n # (marker.pose.position.x , marker.pose.position.y) = self.idx2XY(idx)\n self.markerArray.markers.append(marker)\n \n def pose_quaternion_2_list(self, quaternion):\n \"\"\"\n This function help transfer the geometry_msgs.msg.PoseStameped \n into (translation, quaternion) <-- lists\n \"\"\"\n return [quaternion.x, quaternion.y, quaternion.z, quaternion.w]\n\n#----- Declare Class -----# \nLVP = LINEAR_VELOCITY_PLANNER()\n\ndef main(args):\n #----- Init node ------# \n rospy.init_node('linear_velocity_planner', anonymous=True)\n rospy.Subscriber('/lucky_navi/goal', Pose2D , LVP.goal_CB) # TODO for testing \n # rospy.Subscriber('/move_base_simple/goal', Pose2D , LVP.goal_CB)\n rospy.Subscriber('/current_position', PoseStamped, LVP.current_position_CB) \n\n\n r = rospy.Rate(10)#call at 10HZ\n while (not rospy.is_shutdown()):\n '''\n if GC.is_need_pub: \n pub_global_costmap.publish(GC.global_costmap)\n GC.is_need_pub = False\n if GP.is_need_pub:\n pub_global_path.publish(GP.global_path)\n GP.is_need_pub = False\n '''\n LVP.iterateOnce()\n r.sleep()\n\nif __name__ == '__main__':\n try:\n main(sys.argv)\n except rospy.ROSInterruptException:\n pass\n\n \n\n","sub_path":"src/linear_velocity_planner.py","file_name":"linear_velocity_planner.py","file_ext":"py","file_size_in_byte":10365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"193081725","text":"import logging\nimport os\nimport pickle\nimport numpy as np\n\nfrom .io import load_jets_from_pickle, save_jets_to_pickle\nfrom .JetDataset import JetDataset\n\ndef load_jets(data_dir, filename, redo=False, preprocess_fn=None):\n\n #preprocessed_dir = os.path.join(data_dir, 'preprocessed')\n\n raw_data_dir = os.path.join(data_dir, 'raw')\n preprocessed_dir = os.path.join(data_dir, 'preprocessed')\n path_to_preprocessed = os.path.join(preprocessed_dir, filename)\n\n if not os.path.exists(path_to_preprocessed) or redo:\n if not os.path.exists(preprocessed_dir):\n os.makedirs(preprocessed_dir)\n\n logging.warning(\"Preprocessing...\")\n\n preprocess_fn(raw_data_dir, preprocessed_dir, filename)\n\n logging.warning(\"Preprocessed the data and saved it to {}\".format(path_to_preprocessed))\n else:\n logging.warning(\"Data at {} and already preprocessed\".format(path_to_preprocessed))\n\n jets = load_jets_from_pickle(path_to_preprocessed)\n logging.warning(\"\\tSuccessfully loaded data\")\n return jets\n\ndef load_train_dataset(data_dir, filename, n_train, n_valid, redo):\n if 'w-vs-qcd' in data_dir:\n from .w_vs_qcd import preprocess, crop_dataset\n elif 'quark-gluon' in data_dir:\n from .quark_gluon import preprocess, crop_dataset\n else:\n raise ValueError('Unrecognized data_dir!')\n #from problem_module import preprocess, crop_dataset\n\n problem = data_dir.split('/')[-1]\n subproblem = filename\n\n logging.warning(\"Loading data...\")\n filename = \"{}-train.pickle\".format(filename)\n\n jets = load_jets(data_dir, filename, redo, preprocess_fn=preprocess)\n logging.warning(\"Found {} jets in total\".format(len(jets)))\n\n if n_train > 0:\n jets = jets[:n_train]\n logging.warning(\"Splitting into train and validation...\")\n #\n train_jets = jets[n_valid:]\n train_dataset = JetDataset(train_jets)\n #\n valid_jets = jets[:n_valid]\n valid_dataset = JetDataset(valid_jets)\n\n # crop validation set and add the excluded data to the training set\n #if 'w-vs-qcd' in data_dir:\n valid_dataset, cropped_dataset = crop_dataset(valid_dataset, pileup=False)\n train_dataset.extend(cropped_dataset)\n\n train_dataset.shuffle()\n ##\n logging.warning(\"Building normalizing transform from training set...\")\n train_dataset.transform()\n\n valid_dataset.transform(train_dataset.tf)\n\n # add cropped indices to training data\n logging.warning(\"\\tfinal train size = %d\" % len(train_dataset))\n logging.warning(\"\\tfinal valid size = %d\" % len(valid_dataset))\n\n return train_dataset, valid_dataset\n\ndef load_test_dataset(data_dir, filename, n_test, redo):\n if 'w-vs-qcd' in data_dir:\n from .w_vs_qcd import preprocess, crop_dataset\n elif 'quark-gluon' in data_dir:\n from .quark_gluon import preprocess, crop_dataset\n else:\n raise ValueError('Unrecognized data_dir!')\n\n train_dataset, _ = load_train_dataset(data_dir, filename, -1, 27000, False)\n logging.warning(\"Loading test data...\")\n filename = \"{}-test.pickle\".format(filename)\n jets = load_jets(data_dir, filename, redo)\n jets = jets[:n_test]\n\n dataset = JetDataset(jets)\n dataset.transform(train_dataset.tf)\n\n # crop validation set and add the excluded data to the training set\n dataset, _ = crop_dataset(dataset, pileup=False)\n\n # add cropped indices to training data\n logging.warning(\"\\tfinal test size = %d\" % len(dataset))\n\n return dataset\n","sub_path":"src/jets/data_ops/load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"587638528","text":"# -*- coding: utf-8 -*-\nimport h5py\nimport numpy as np\nimport os\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms, models\nimport pytorch_lightning as pl\nfrom pytorch_lightning.loggers import WandbLogger\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport wandb\nwandb.init(\n # mode='offline',\n project=\"prostatex\", \n group=\"wang-tbakd3-t3\",\n config={\n \"loss\": \"binary_cross_entropy\",\n \"metric\": \"accuracy\",\n \"optimizer\": \"Adam\",\n \"lr\":1e-4,\n \"epoch\": 1000,\n \"batch_size\": 16,\n \"augmentation\": {\n \"degrees\": 50,\n \"translate\": (0.9, 0.9),\n \"shear\": [-15, 15, -15, 15],\n },\n \"train_dir\": 'tbakd3_npy/train',\n \"valid_dir\": 'tbakd3_npy/valid_bal'\n })\nwandblogger = WandbLogger()\n\nnp.random.seed(0)\ntorch.manual_seed(0)\n\n\n## Data\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.RandomAffine(**wandb.config.augmentation)\n])\n\ndef npy_loader(path: str) -> np.ndarray:\n return np.load(path)\n\ndatasets = {}\ndatasets['train'] = torchvision.datasets.DatasetFolder(wandb.config.train_dir, extensions='npy', loader=npy_loader, transform=transform)\ndatasets['valid'] = torchvision.datasets.DatasetFolder(wandb.config.valid_dir, extensions='npy', loader=npy_loader, transform=transforms.ToTensor())\n\n\nclass MSDSC(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(16, 16, 3, padding=1, groups=16),\n nn.Conv2d(16, 8, 1)\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(16, 16, 5, padding=2, groups=16),\n nn.Conv2d(16, 8, 1)\n )\n self.layer = nn.Sequential(\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\n def forward(self, x):\n x1 = self.conv1(x)\n x2 = self.conv2(x)\n x = torch.cat((x1, x2), 1)\n x = self.layer(x)\n return x\n\n\nclass WangClassifier(pl.LightningModule):\n\n def __init__(self, num_sequences):\n super().__init__()\n\n self.num_sequences = num_sequences\n self.conv = nn.ModuleList(\n [nn.Sequential(\n MSDSC(), MSDSC(), MSDSC(), MSDSC(), MSDSC(), nn.Flatten()\n ) for i in range(num_sequences)]\n )\n self.linear = nn.ModuleList([nn.Linear(64, 1) for i in range(num_sequences)])\n self.fusion = nn.Linear(64 * num_sequences, 1)\n\n self.lr = wandb.config.lr\n self.accuracy = lambda x, y: ((x > 0.5).type_as(y) == y).float().mean()\n self.auroc = pl.metrics.functional.classification.auroc\n\n def forward(self, x):\n conv = [conv(x[:, i].unsqueeze(1).repeat(1, 16, 1, 1)) for i, conv in enumerate(self.conv)]\n conv_x = torch.cat([c.unsqueeze(1) for c in conv], 1)\n linear = [linear(conv_x[:, i]) for i, linear in enumerate(self.linear)]\n linear_x = torch.cat([l.unsqueeze(1) for l in linear], 1)\n fusion_x = self.fusion(torch.cat(conv, 1)).unsqueeze(1)\n x = torch.cat((linear_x, fusion_x), 1)\n x = torch.mean(linear_x, 1)\n return x\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n y_hat = self(x)\n y = y.type_as(y_hat).unsqueeze(1)\n criterion = nn.BCEWithLogitsLoss()\n loss = criterion(y_hat, y)\n acc = self.accuracy(torch.sigmoid(y_hat), y)\n self.log('train_loss', loss, sync_dist=True)\n self.log('train_acc', acc, prog_bar=True, sync_dist=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n y_hat = self(x)\n y = y.type_as(y_hat).unsqueeze(1)\n criterion = nn.BCEWithLogitsLoss()\n loss = criterion(y_hat, y)\n acc = self.accuracy(torch.sigmoid(y_hat), y)\n auc = self.auroc(torch.sigmoid(y_hat).squeeze(), y.squeeze())\n self.log('valid_loss', loss, sync_dist=True)\n self.log('valid_acc', acc, prog_bar=True, sync_dist=True)\n self.log('valid_auc', auc, prog_bar=True, sync_dist=True)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n return optimizer\n \n def train_dataloader(self):\n dataloader = torch.utils.data.DataLoader(\n datasets['train'], \n batch_size=wandb.config.batch_size, \n num_workers=16, drop_last=True, shuffle=True)\n return dataloader\n\n def val_dataloader(self):\n dataloader = torch.utils.data.DataLoader(\n datasets['valid'], \n batch_size=64, \n num_workers=16, drop_last=False)\n return dataloader\n\n\nmodel = WangClassifier(num_sequences=datasets['train'][0][0].shape[0])\ntrainer = pl.Trainer(\n logger=wandblogger,\n gpus=-1,\n accelerator='ddp',\n max_epochs=wandb.config.epoch)\ntrainer.fit(model)","sub_path":"wang.py","file_name":"wang.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"492319955","text":"\"\"\"\n@author: Churiulin Evgenii\nСкрипт предназначен для запуска алгоритма машинного обучения Random Forest, метода главных компонент и факторного анализа\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import FactorAnalysis\n\n\n#########################\n# Функция 1 для коррекции пустых значений с учетом предыдущего и следующего значения\n#########################\n\n# colums_df_stat - имя переменной (тип - объект Series), полученной на основе выгрузки данных из исходного массива данных\ndef nan_values_correction(colums_df_stat):\n for tmin2m_st, k in enumerate(colums_df_stat):\n if (tmin2m_st < (len(colums_df_stat)-1)): \n if np.isnan(colums_df_stat[tmin2m_st]) and colums_df_stat[tmin2m_st-1] != 0 and colums_df_stat[tmin2m_st+1] != 0:\n colums_df_stat[tmin2m_st] = (colums_df_stat[tmin2m_st - 1] + colums_df_stat[tmin2m_st + 1])/2 \n elif np.isnan(colums_df_stat[tmin2m_st]) and colums_df_stat[tmin2m_st-1] != 0 and colums_df_stat[tmin2m_st+2] != 0:\n colums_df_stat[tmin2m_st] = (colums_df_stat[tmin2m_st - 1] + colums_df_stat[tmin2m_st + 2])/2\n elif np.isnan(colums_df_stat[tmin2m_st]) and colums_df_stat[tmin2m_st-1] != 0 and colums_df_stat[tmin2m_st+3] != 0:\n colums_df_stat[tmin2m_st] = (colums_df_stat[tmin2m_st - 1] + colums_df_stat[tmin2m_st + 3])/2 \n if tmin2m_st == (len(colums_df_stat)-1): \n if np.isnan(colums_df_stat[tmin2m_st]):\n colums_df_stat[tmin2m_st] = (colums_df_stat[tmin2m_st - 1])\n return (colums_df_stat) \n\n#########################\n# Функция 2 для коррекции пустых значений с учетом предыдущего, следующего, 2 следующих, 3 следующих значения\n#########################\n\n# colums_df_stat2 - имя переменной (тип - объект Series), полученной на основе выгрузки данных из исходного массива данных \ndef nan_values_correction_2(colums_df_stat_2):\n for tt, kkk in enumerate(colums_df_stat_2):\n if (tt < (len(colums_df_stat_2)-1)):\n if np.isnan(colums_df_stat_2[tt]) and not np.isnan(colums_df_stat_2[tt-1]) and not np.isnan(colums_df_stat_2[tt+1]):\n colums_df_stat_2[tt] = (colums_df_stat_2[tt-1] + colums_df_stat_2[tt+1])/2 \n elif np.isnan(colums_df_stat_2[tt]) and not np.isnan(colums_df_stat_2[tt-1]) and not np.isnan(colums_df_stat_2[tt+2]):\n colums_df_stat_2[tt] = (colums_df_stat_2[tt-1] + colums_df_stat_2[tt+2])/2 \n elif np.isnan(colums_df_stat_2[tt]) and not np.isnan(colums_df_stat_2[tt-1]) and not np.isnan(colums_df_stat_2[tt+3]):\n colums_df_stat_2[tt] = (colums_df_stat_2[tt-1] + colums_df_stat_2[tt+3])/2\n if tt == (len(colums_df_stat_2)-1):\n if np.isnan(colums_df_stat_2[tt]):\n colums_df_stat_2[tt] = colums_df_stat_2[tt-1]\n return (colums_df_stat_2) \n\n# Примечание функции 1 и 2 можно заменить одной, но требуется доработка + дополнительно следует учесть когда пропуск стоит на 1 месте\n\n\n#########################\n# Функция 3 для коррекции пустых значения за период с мая по октябрь (не включая). Использовал для заполнения \n#########################\n\n# пустых значений снежного покрова\n# colums_snow - имя переменной (тип - объект Series), полученной на основе выгрузки д��нных из исходного массива данных \ndef snow_values_correction(colums_snow):\n for h_st, kk in enumerate(colums_snow):\n month = colums_snow.index[h_st].month\n if month >= 5 and month <= 9:\n colums_snow[h_st] = 0\n return (colums_snow)\n\n#########################\n# Функция 4 для загрузки исходных метеорологических данных\n#########################\n \n# iPath - путь к данным \ndef initial_data(iPath):\n # Считываем данные \n df = pd.read_csv(iPath, skiprows = 0, sep=';', dayfirst = True, parse_dates = True)\n #print ('Columns:', df.columns)\n #Удаляем дубликаты и столбцы, которые не представляют интереса для данного исследования \n df = df.drop_duplicates(keep = False)\n df = df.drop(['lat','lon','h_station','id_st','t2m_negative','hsnow'], axis=1) \n #Создаем серии для заполнения пропусков в даннных\n index_date = pd.to_datetime(df['Date']) # time step\n ps = pd.Series(df['ps'].values, index = index_date, dtype = 'float') # air pressure at meteostation\n pmsl = pd.Series(df['pmsl'].values, index = index_date, dtype = 'float') # air pressure at meteostation in according to see level\n t2m = pd.Series(df['t2m'].values, index = index_date, dtype = 'float') # 2m air temperature\n tmin2m = pd.Series(df['tmin2m'].values, index = index_date, dtype = 'float') # 2m min air temperature\n tmax2m = pd.Series(df['tmax2m'].values, index = index_date, dtype = 'float') # 2m max air temperature \n tming = pd.Series(df['tming'].values, index = index_date, dtype = 'float') # min soil temperature for night \n td2m = pd.Series(df['td2m'].values, index = index_date, dtype = 'float') # 2m dew point\n t_g = pd.Series(df['t_g'].values, index = index_date, dtype = 'float') # temperatura of soil\n dd10m = pd.Series(df['dd10m'].values, index = index_date, dtype = 'float') # direction of wind\n ff10mean = pd.Series(df['ff10meam'].values, index = index_date, dtype = 'float') # speed of wind\n ff10max = pd.Series(df['ff10max'].values, index = index_date, dtype = 'float') # speed of wind\n hsnow = pd.Series(df['hsnow_snowe'].values, index = index_date, dtype = 'float') # Depth of snow\n swe = pd.Series(df['swe'].values, index = index_date, dtype = 'float') # SWE of snow\n rho = pd.Series(df['rho'].values, index = index_date, dtype = 'float') # RHO of snow \n # Запускаем функции коррекции данных\n ps = nan_values_correction(ps)\n pmsl = nan_values_correction(pmsl)\n t2m = nan_values_correction(t2m)\n tmin2m = nan_values_correction(tmin2m)\n tmax2m = nan_values_correction(tmax2m)\n tming = nan_values_correction(tming)\n tming = nan_values_correction_2(tming)\n td2m = nan_values_correction(td2m)\n t_g = nan_values_correction(t_g)\n t_g = nan_values_correction_2(t_g)\n for t_g_s, kk in enumerate(t_g):\n if (t_g_s < (len(t_g)-1)):\n if np.isnan(t_g[t_g_s]) and not np.isnan(tming[t_g_s]):\n t_g[t_g_s] = tming[t_g_s] \n if t_g_s == (len(t_g)-1):\n if np.isnan(t_g[t_g_s]):\n t_g[t_g_s] = tming[t_g_s]\n dd10m = nan_values_correction(dd10m)\n ff10mean = nan_values_correction(ff10mean)\n ff10max = nan_values_correction(ff10max)\n hsnow = snow_values_correction(hsnow)\n swe = snow_values_correction(swe)\n rho = snow_values_correction(rho) \n # Отбрасываем строки с пустыми значениям, где заполненных параметров меньше 15\n df = df.dropna(axis='rows', thresh=15) \n # Выполняем переиндексирование по дате\n df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') \n # Устанавливаем новый индекс для массива данных\n df = df.set_index('Date') \n # Заполняем оставшиеся пустые значения в столбцах средним значением по столбцу \n #df = df.fillna(method='ffill')\n #df = df.fillna(df.mean())\n #df = df.fillna(0) \n return (df) \n\n#########################\n# Функция для выборки только зимних значений метеопараметров\n#########################\n\n# data_maket - пустой массив данных, куда будут записываться данные\n# df_data - массив с метеоданными\n# name - текстовый параметр с именем столбца из df_data\n# time_1 - переменная начала периода\n# time_2 - переменная конца периода \ndef winter_data(data_maket, df_data, name, time_1, time_2):\n if len(data_maket)>0: \n data_maket = pd.concat([data_maket, df_data[name][time_1:time_2]])\n else:\n data_maket = df_data[name][time_1:time_2]\n return (data_maket)\n\n#########################\n# Функция выполняющая простейшее машинное обучение на основе метода RandomForest\n#########################\n\n# df_main_year или df_main_winter = df - массив по которому выполняем описание\n# Data_path_exit - путь, где будет храниться результат работы \ndef simple_machine_learning(df_data, Data_path_exit):\n # Выбрасываем интересующий нас столбец из подготовленного массива данных и создаем 2 новых переменных\n X = df_data.drop('Discharge', axis=1)\n y = df_data['Discharge']\n\n # Разделяем наши данные на тестовый набор данных и независимый набор данных для провеки\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.50, random_state=2020)\n\n # Стандартизируем данные\n ss = StandardScaler()\n X_train_scaled = ss.fit_transform(X_train)\n X_test_scaled = ss.transform(X_test)\n\n # Переводим из объекта Series в объект numpy\n y_train = np.array(y_train)\n # Переводим из float 64 в int 32, нужно для корректной работы методов дальше\n y_train = y_train.astype(np.int32)\n\n # Подключаем алгоритм машинного обучения и выполняем обучение базовой модели \n rfc = RandomForestClassifier()\n rfc.fit(X_train_scaled, y_train)\n #display(rfc.score(X_train_scaled, y_train))\n\n # Отображаем самые важные признаки для обучения \n feats = {}\n # Требуется указать какие данные используются\n for feature, importance in zip(df_data.columns, rfc.feature_importances_): \n feats[feature] = importance\n importances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini-Importance'})\n importances = importances.sort_values(by='Gini-Importance', ascending=False)\n importances = importances.reset_index()\n importances = importances.rename(columns={'index': 'Features'})\n sns.set(font_scale = 5)\n sns.set(style=\"whitegrid\", color_codes=True, font_scale = 1.7)\n fig, ax = plt.subplots()\n fig.set_size_inches(30,15)\n sns.barplot(x=importances['Gini-Importance'], y=importances['Features'], data=importances, color='skyblue')\n plt.xlabel('Значимость переменной', fontsize=25, weight = 'bold')\n plt.ylabel('Переменные', fontsize=25, weight = 'bold')\n #plt.title('Feature Importance', fontsize=25, weight = 'bold')\n plt.savefig(Data_path_exit + 'Importance factor' + '.png', format='png', dpi = 300) \n # Отображаем графически важность признаков\n display(plt.show())\n # Делаем визуализацию важности признаков\n display(importances)\n \n ###### Запускаем метод главных компонент \n pca_test = PCA(n_components=13)\n pca_test.fit(X_train_scaled)\n sns.set(style='whitegrid')\n plt.plot(np.cumsum(pca_test.explained_variance_ratio_))\n plt.xlabel('Число компонент')\n plt.ylabel('Суммарно объясненная дисперсия')\n plt.axvline(linewidth=4, color='r', linestyle = '--', x=10, ymin=0, ymax=1)\n plt.savefig(Data_path_exit + 'PCA' + '.png', format='png', dpi = 300) \n display(plt.show())\n evr = pca_test.explained_variance_ratio_\n cvr = np.cumsum(pca_test.explained_variance_ratio_)\n pca_df = pd.DataFrame()\n pca_df['Cumulative Variance Ratio'] = cvr\n pca_df['Explained Variance Ratio'] = evr\n #display(pca_df.head(10)) \n # Понижаем размерность исходного массива данных до n-компонент описывающих 95% дисперсии\n pca = PCA(n_components=10)\n pca.fit(X_train_scaled)\n X_train_scaled_pca = pca.transform(X_train_scaled)\n X_test_scaled_pca = pca.transform(X_test_scaled)\n \n # Создаем новый массив данных с распределением дисперсии по компонентам\n pca_dims = []\n for x in range(0, len(pca_df)):\n pca_dims.append('PCA Component {}'.format(x))\n pca_test_df = pd.DataFrame(pca_test.components_, columns=X.columns, index=pca_dims)\n pca_test_df.to_csv(Data_path_exit + 'PCA_result.csv', sep=';', float_format='%.3f') # массив данных с распределением дисперсии по компонентам\n #print (pca_test_df.head(10).T)\n\n#########################\n# Функция для стандартизации переменных\n#########################\n \n# df - исходный массив с данными\ndef scale_features(df):\n scaled = preprocessing.StandardScaler().fit_transform(df)\n scaled = pd.DataFrame(scaled, columns=df.columns)\n return scaled\n\n#########################\n# Функция для выполнения факторного анализа\n#########################\n \n# df_main_year или df_main_winter = df - массив по которому выполняем описание\n# Data_path_exit - путь к папкам, где будут храниться данные\n# df2_index - массив с исходными индексами по дате (может быть 2 варианта либо df_main (4 сезона) или df_main1 (холодный сезон))\ndef factor_analysis(df, Data_path_exit, df2_index):\n # Выполняем расчет описательной статистики и корреляционной матрицы\n df_des_stat = df.describe()\n df_cor_stat = df.corr()\n # Делаем вывод описательной статистики и корреляционной матрицы\n df_des_stat.to_csv(Data_path_exit + 'des_stat.csv', sep=';', float_format='%.3f')\n df_cor_stat.to_csv(Data_path_exit + 'cor_stat.csv', sep=';', float_format='%.3f')\n # Строим диаграммы рассеивания и гистограммы\n matrix = scatter_matrix(df, figsize=[20,20], alpha=0.2)\n # Импортируем данные\n plt.savefig(Data_path_exit + 'Scatter_matrix' +'.png', format='png', dpi = 300)\n\n df_scaled = preprocessing.scale(df) # массив со стандартизированными данными\n # Проецируем с метода главных компонент переменнные на плоскость. Выделяем 4 главных фактора (можно больше)\n pca = PCA(n_components=4)\n pca1 = pca.fit(df_scaled)\n print('Доля разброса, которую объясняют факторы: ', pca.explained_variance_ratio_)\n \n # Рассчитываем значения основных факторов\n zzz = pca.transform(df_scaled)\n values_factors = pd.DataFrame(zzz)\n values_factors.to_csv(Data_path_exit + 'factor_values.csv', sep=';', float_format='%.3f') \n #print (zzz)\n\n # Факторный анализ\n fa = FactorAnalysis(n_components=4) # Количество факторов\n fac_1 = fa.fit(df_scaled)\n df_fa = pd.DataFrame(fa.components_, columns=df.columns) \n df_fa.to_csv(Data_path_exit + 'factor_result.csv', sep=';', float_format='%.3f') # Координаты факторов в пространстве исходных значений\n # Уникальность значений в смысле дисперсии, объяснённой факторами (чем больше, тем хуже объясняется факторами) содержится в атрибуте\n fac_2 = pd.Series(fa.noise_variance_, df.columns)\n fac_2.to_csv(Data_path_exit + 'Unic_values.csv', sep=';', float_format='%.3f') # Координаты факторов. Основной результат \n print ('Уникальность значений:\\n', fac_2)\n scores = pd.DataFrame(fa.transform(df_scaled), columns=['factor1', 'factor2','factor3', 'factor4']) \n scores = scores.set_index(df2_index.index)\n scores.to_csv(Data_path_exit + 'factor_vectors.csv', sep=';', float_format='%.3f') # Координаты факторов. Основной результат\n\n\n###### Этап 1. Подготовка начальных данных для проведения дальнейших вычислений\n\n# Создание массивов метеоданных для водосборов\n\n# Путь к папке, где хранится проект с рекой Дон\npath_main = 'D:/Don/'\n# Путь к папкам, куда записываются результирующие данные\niPath_result = path_main +'Main_data/' #Результирующие массивы с метео данными\niPath_exit = path_main +'PCA/' #Результаты машинного обучения, PCA и факторного анализа\n\n###### Река Сосна - г.п. Елец\niPath_stat_exit1 = iPath_exit + 'Sosna_river/annual_data/' #Результаты для всех сезонов\niPath_stat_exit2 = iPath_exit + 'Sosna_river/cold_data/' #Результаты для холодного сезона\n\n###### Река Битюг - г.п. Бобров\niPath_stat_exit3 = iPath_exit + 'Bitug_river/annual_data/' #Результаты для всех сезонов\niPath_stat_exit4 = iPath_exit + 'Bitug_river/cold_data/' #Результаты для холодного сезона\n\n###### Река Тихая Сосна - г.п. Алексеевка\niPath_stat_exit5 = iPath_exit + 'M_Sosna_river/annual_data/' #Результаты для всех сезонов\niPath_stat_exit6 = iPath_exit + 'M_Sosna_river/cold_data/' #Результаты для холодного сезона\n\n###### Река Медведица - г.п. Лысые горы\niPath_stat_exit7 = iPath_exit + 'Medveditsa_river/annual_data/' #Результаты для всех сезонов\niPath_stat_exit8 = iPath_exit + 'Medveditsa_river/cold_data/' #Результаты для холодного сезона\n\n\n######\n#Версия для р. Сосна - г.п. Елец (метеостанции 27928, 27915, 34013, 34112)\n######\n\"\"\"\nfileName_1 = '27928.csv'\nfileName_2 = '27915.csv'\nfileName_3 = '34013.csv'\nfileName_4 = '34112.csv'\n\niPath_1 = path_main + 'meteo_2000_2020/{}'.format(fileName_1)\niPath_2 = path_main + 'meteo_2000_2020/{}'.format(fileName_2)\niPath_3 = path_main + 'meteo_2000_2020/{}'.format(fileName_3)\niPath_4 = path_main + 'meteo_2000_2020/{}'.format(fileName_4)\n\n# Загружаем массивы с метеоданными\ndf_27928 = initial_data(iPath_1)\ndf_27915 = initial_data(iPath_2)\ndf_34013 = initial_data(iPath_3)\ndf_34112 = initial_data(iPath_4)\n\n# Создаем общий массив и усредняем значения метеопараметров\ndf_data = pd.concat((df_27928, df_27915,df_34013,df_34112)).groupby(level=0).mean()\n\n# Подгружаем данные гидрологических наблюдений\nfileName_hydro = 'Rivers_discharges.xlsx'\niPath_hydro = path_main + 'hydro_data/{}'.format(fileName_hydro)\n\ndf_hydro = pd.read_excel(iPath_hydro, skiprows = 0, sep=';', dayfirst = True, parse_dates = True, index_col = [0], \n skipinitialspace = True, na_values= ['9990','********'])\nprint ('Columns:', df_hydro.columns)\ndata_rivers = df_hydro['Sosna']\n\"\"\"\n######\n#Версия для р. Битюг - г.п. Бобров (метеостанции 34036, 34238)\n######\n\"\"\"\nfileName_1 = '34036.csv'\nfileName_2 = '34238.csv'\n\niPath_1 = path_main + 'meteo_2000_2020/{}'.format(fileName_1)\niPath_2 = path_main + 'meteo_2000_2020/{}'.format(fileName_2)\n\n# Загружаем массивы с метеоданными\ndf_34036 = initial_data(iPath_1)\ndf_34238 = initial_data(iPath_2)\n\n# Создаем общий массив и усредняем значения метеопараметров\ndf_data = pd.concat((df_34036, df_34238)).groupby(level=0).mean()\n\n# Подгружаем данные гидрологических наблюдений\nfileName_hydro = 'Rivers_discharges.xlsx'\niPath_hydro = path_main + 'hydro_data/{}'.format(fileName_hydro)\n\ndf_hydro = pd.read_excel(iPath_hydro, skiprows = 0, sep=';', dayfirst = True, parse_dates = True, index_col = [0], \n skipinitialspace = True, na_values= ['9990','********'])\nprint ('Columns:', df_hydro.columns)\ndata_rivers = df_hydro['Bitug']\n\"\"\"\n######\n#Версия для р. Тихая Сосна - г.п. Алексеевка (метеостанции 34213, 34321)\n######\n\"\"\"\nfileName_1 = '34213.csv'\nfileName_2 = '34321.csv'\n\niPath_1 = path_main + 'meteo_2000_2020/{}'.format(fileName_1)\niPath_2 = path_main + 'meteo_2000_2020/{}'.format(fileName_2)\n\n# Загружаем массивы с метеоданными\ndf_34213 = initial_data(iPath_1)\ndf_34321 = initial_data(iPath_2)\n\n# Создаем общий массив и усредняем значения метеопараметров\ndf_data = pd.concat((df_34213, df_34321)).groupby(level=0).mean()\n\n# Подгружаем данные гидрологических наблюдений\nfileName_hydro = 'Rivers_discharges.xlsx'\niPath_hydro = path_main + 'hydro_data/{}'.format(fileName_hydro)\n\ndf_hydro = pd.read_excel(iPath_hydro, skiprows = 0, sep=';', dayfirst = True, parse_dates = True, index_col = [0], \n skipinitialspace = True, na_values= ['9990','********'])\nprint ('Columns:', df_hydro.columns)\ndata_rivers = df_hydro['Tixay Sosna']\n\"\"\"\n######\n#Версия для р. Медведица - г.п. Лысые Горы (метеостанции 34063, 34069, 34163)\n######\n\nfileName_1 = '34063.csv'\nfileName_2 = '34069.csv'\nfileName_3 = '34163.csv'\n\niPath_1 = path_main + 'meteo_2000_2020/{}'.format(fileName_1)\niPath_2 = path_main + 'meteo_2000_2020/{}'.format(fileName_2)\niPath_3 = path_main + 'meteo_2000_2020/{}'.format(fileName_3)\n\n# Загружаем массивы с метеоданными\ndf_34063 = initial_data(iPath_1)\ndf_34069 = initial_data(iPath_2)\ndf_34163 = initial_data(iPath_3)\n\n# Создаем общий массив и усредняем значения метеопараметров\ndf_data = pd.concat((df_34063, df_34069, df_34163)).groupby(level=0).mean()\n\n# Подгружаем данные гидрологических наблюдений\nfileName_hydro = 'Rivers_discharges.xlsx'\niPath_hydro = path_main + 'hydro_data/{}'.format(fileName_hydro)\n\ndf_hydro = pd.read_excel(iPath_hydro, skiprows = 0, sep=';', dayfirst = True, parse_dates = True, index_col = [0], \n skipinitialspace = True, na_values= ['9990','********'])\nprint ('Columns:', df_hydro.columns)\ndata_rivers = df_hydro['Medveditsa']\n\n\n\n\n\n# Объединяем массив с метеоданными с данными о расходах воды\ndf_main = pd.concat((df_data, data_rivers), axis = 1)\n\n# Отбрасываем строки с пустыми значениям, где заполненных параметров меньше 15. Для того чтобы отфльтровать лишние расходы воды\ndf_main = df_main.dropna(axis='rows', thresh=15) \n\n# Отбрасываем \"ненужные\" или дублирующие столбцы данных \ndf_main = df_main.drop(['tming','pmsl','dd10m','R12','R24'], axis=1) # Основной массив с метеоданными\n\n# Заполняем оставшиеся пустые значения в столбцах средним значением по столбцу\n# Формируем датафрейм с информацией о всех метеоданных за весь год (с января по декабрь)\ndf_main = df_main.fillna(df_main.mean())\n\n# Нужно правильно указывать столбец из которого были взяты расход воды\n#df_main = df_main.rename(columns={'Sosna': 'Discharge'})\n#df_main = df_main.rename(columns={'Bitug': 'Discharge'})\n#df_main = df_main.rename(columns={'Tixay Sosna': 'Discharge'})\ndf_main = df_main.rename(columns={'Medveditsa': 'Discharge'})\n\n\n\n###### Этап 2. Готовим данные для всех сезонов\n# Делаем переиндексацию и отбрасываем дату\ncount = [] \ncount_numbers = 0\nfor jj in range(len(df_main)):\n count_numbers += 1 \n count.append(count_numbers)\nt = pd.Series(count, index = df_main.index) \ndf_main_year = df_main.set_index(t) # Итоговый массив данных для все 4 сезонов\n\n\n\n###### Этап 3. Готовим данные для зимнего сезона\n# Создаем специальный массив с данными только за зимний период годы, чтобы посмотреть влияние снега на весеннее половодье\n# Создаем пустые списки для переменных\nps_winter = ''\nt2m_winter = ''\ntmin2m_winter = ''\ntmax2m_winter = ''\nt_g_winter = ''\ntd2m_winter = ''\nff10meam_winter = ''\nff10max_winter = ''\nhsnow_snowe_winter = ''\nrho_winter = ''\nswe_winter = ''\nR12_liquid_winter = ''\nR12_solid_winter = ''\nDischarge_winter = ''\n\n# Задаем количество периодов = количеству зимних сезонов\nw = 20 \n \nperiods_winter = [['2000-10-01','2001-04-30'],\n ['2001-10-01','2002-04-30'],\n ['2002-10-01','2003-04-30'],\n ['2003-10-01','2004-04-30'],\n ['2004-10-01','2005-04-30'],\n ['2005-10-01','2006-04-30'],\n ['2006-10-01','2007-04-30'],\n ['2007-10-01','2008-04-30'],\n ['2008-10-01','2009-04-30'],\n ['2009-10-01','2010-04-30'],\n ['2010-10-01','2011-04-30'],\n ['2011-10-01','2012-04-30'],\n ['2012-10-01','2013-04-30'],\n ['2013-10-01','2014-04-30'],\n ['2014-10-01','2015-04-30'],\n ['2015-10-01','2016-04-30'],\n ['2016-10-01','2017-04-30'],\n ['2017-10-01','2018-04-30'],\n ['2018-10-01','2019-04-30'],\n ['2019-10-01','2020-04-30']]\n\nperiods_winter = np.array(periods_winter)\nfor tr in range(w):\n try:\n y_w_1 = periods_winter[tr][0]\n y_w_2 = periods_winter[tr][1]\n \n ps_winter = winter_data(ps_winter, df_main, 'ps', y_w_1, y_w_2) \n t2m_winter = winter_data(t2m_winter, df_main, 't2m', y_w_1, y_w_2) \n tmin2m_winter = winter_data(tmin2m_winter, df_main, 'tmin2m', y_w_1, y_w_2) \n tmax2m_winter = winter_data(tmax2m_winter, df_main, 'tmax2m', y_w_1, y_w_2) \n t_g_winter = winter_data(t_g_winter, df_main, 't_g', y_w_1, y_w_2) \n td2m_winter = winter_data(td2m_winter, df_main, 'td2m', y_w_1, y_w_2)\n ff10meam_winter = winter_data(ff10meam_winter, df_main, 'ff10meam', y_w_1, y_w_2)\n ff10max_winter = winter_data(ff10max_winter, df_main, 'ff10max', y_w_1, y_w_2) \n hsnow_snowe_winter = winter_data(hsnow_snowe_winter, df_main, 'hsnow_snowe', y_w_1, y_w_2)\n rho_winter = winter_data(rho_winter, df_main, 'rho', y_w_1, y_w_2)\n swe_winter = winter_data(swe_winter, df_main, 'swe', y_w_1, y_w_2)\n R12_liquid_winter = winter_data(R12_liquid_winter, df_main, 'R12_liquid', y_w_1, y_w_2)\n R12_solid_winter = winter_data(R12_solid_winter, df_main, 'R12_solid', y_w_1, y_w_2)\n Discharge_winter = winter_data(Discharge_winter, df_main, 'Discharge', y_w_1, y_w_2) \n except:\n print ('No data')\n\ndf_main_winter = pd.concat([ps_winter, t2m_winter, tmin2m_winter, tmax2m_winter, t_g_winter,\n td2m_winter, ff10meam_winter, ff10max_winter, hsnow_snowe_winter,\n rho_winter, swe_winter, R12_liquid_winter, R12_solid_winter,\n Discharge_winter], axis = 1)\n\ndf_main1 = df_main_winter # Создаем специальный массив для сохранения индекса с датой для факторного анализа\n# Делаем переиндексацию и отбрасываем дату\ncount2 = [] \ncount_numbers_2 = 0\nfor jjj in range(len(df_main_winter)):\n count_numbers_2 += 1 \n count2.append(count_numbers_2)\n\nt2 = pd.Series(count2, index = df_main_winter.index) \ndf_main_winter = df_main_winter.set_index(t2) # Итоговый массив данных для зимних сезонов\n\n\n###### Река Сосна - г.п. Елец\n\"\"\"\n###### Этап 4. Машинное обучение и Факторный анализ\nprint ('4 сезона')\nannual_data_m = simple_machine_learning(df_main_year, iPath_stat_exit1)\nannual_data_f = factor_analysis(df_main_year, iPath_stat_exit1, df_main)\nprint ('Холодный сезон')\ncold_data_m = simple_machine_learning(df_main_winter, iPath_stat_exit2)\ncold_data_f = factor_analysis(df_main_winter, iPath_stat_exit2, df_main1)\n\"\"\"\n\n###### Река Битюг - г.п. Бобров\n\"\"\"\n###### Этап 4. Машинное обучение и Факторный анализ\nprint ('4 сезона')\nannual_data_m = simple_machine_learning(df_main_year, iPath_stat_exit3)\nannual_data_f = factor_analysis(df_main_year, iPath_stat_exit3, df_main)\nprint ('Холодный сезон')\ncold_data_m = simple_machine_learning(df_main_winter, iPath_stat_exit4)\ncold_data_f = factor_analysis(df_main_winter, iPath_stat_exit4, df_main1)\n\"\"\"\n\n\n###### Река Тихая Сосна - г.п. Алексеевка\n\"\"\"\n###### Этап 4. Машинное обучение и Факторный анализ\nprint ('4 сезона')\nannual_data_m = simple_machine_learning(df_main_year, iPath_stat_exit5)\nannual_data_f = factor_analysis(df_main_year, iPath_stat_exit5, df_main)\nprint ('Холодный сезон')\ncold_data_m = simple_machine_learning(df_main_winter, iPath_stat_exit6)\ncold_data_f = factor_analysis(df_main_winter, iPath_stat_exit6, df_main1)\n\"\"\"\n\n###### Река Медведица - г.п. Лысые Горы\n\n###### Этап 4. Машинное обучение и Факторный анализ\nprint ('4 сезона')\nannual_data_m = simple_machine_learning(df_main_year, iPath_stat_exit7)\nannual_data_f = factor_analysis(df_main_year, iPath_stat_exit7, df_main)\nprint ('Холодный сезон')\ncold_data_m = simple_machine_learning(df_main_winter, iPath_stat_exit8)\ncold_data_f = factor_analysis(df_main_winter, iPath_stat_exit8, df_main1)\n\n\n\n\n\n\n\n","sub_path":"PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":33215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"267625799","text":"import torch\nimport numpy as np\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\nclass LovaszLoss(nn.Module):\n\n def __init__(self):\n super().__init__() \n return None\n\n def __gradient__(self, gt_sorted):\n p = len(gt_sorted)\n gts = gt_sorted.sum()\n intersection = gts - gt_sorted.float().cumsum(0)\n union = gts + (1 - gt_sorted).float().cumsum(0)\n jaccard = 1. - intersection / union\n if p > 1:\n jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]\n return jaccard\n \n def __eval__(self, logits, labels):\n signs = 2. * labels.float() - 1.\n errors = (1. - logits * Variable(signs))\n errors_sorted, perm = torch.sort(errors, dim=0, descending=True)\n perm = perm.data\n gt_sorted = labels[perm]\n grad = self.__gradient__(gt_sorted)\n loss = torch.dot(F.relu(errors_sorted), Variable(grad))\n return loss\n \n def mean(self, l, empty=0):\n l = iter(l)\n try:\n n = 1\n acc = next(l)\n except StopIteration:\n if empty == 'raise':\n raise ValueError('Empty mean')\n return empty\n for n, v in enumerate(l, 2):\n acc += v\n if n == 1:\n return acc\n return acc / n\n\n def forward(self, logits, labels):\n loss = []\n for logit, label in zip(logits, labels):\n logit = logit.unsqueeze(0).view(-1)\n label = label.unsqueeze(0).view(-1)\n loss.append(self.__eval__(logit, label))\n return self.mean(loss)\n\n\n","sub_path":"competitions/salt/metrics/lovasz.py","file_name":"lovasz.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"470102763","text":"# gluoncv에 있는 코드 참고\n\n\"\"\"Decoder functions.\nDecoders are used during testing/validation, which convert predictions back to\nnormal boxes, etc.\n\"\"\"\nimport mxnet as mx\nfrom mxnet.gluon import HybridBlock\n\n\nclass BoxDecoder(HybridBlock):\n\n def __init__(self, stds=(0.1, 0.1, 0.2, 0.2), means=(0., 0., 0., 0.)):\n super(BoxDecoder, self).__init__()\n self._stds = stds\n self._means = means\n\n def hybrid_forward(self, F, box_preds, anchors):\n anchor_x, anchor_y, anchor_width, anchor_height = anchors.split(axis=-1, num_outputs=4)\n norm_x, norm_y, norm_width, norm_height = F.split(box_preds, axis=-1, num_outputs=4)\n\n pre_box_x = F.broadcast_add(F.broadcast_mul(norm_x * self._stds[0] + self._means[0], anchor_width), anchor_x)\n pre_box_y = F.broadcast_add(F.broadcast_mul(norm_y * self._stds[1] + self._means[1], anchor_height), anchor_y)\n pre_box_w = F.broadcast_mul(F.exp(norm_width * self._stds[2] + self._means[2]), anchor_width)\n pre_box_h = F.broadcast_mul(F.exp(norm_height * self._stds[3] + self._means[3]), anchor_height)\n\n # center to corner\n half_w = pre_box_w / 2\n half_h = pre_box_h / 2\n xmin = pre_box_x - half_w\n ymin = pre_box_y - half_h\n xmax = pre_box_x + half_w\n ymax = pre_box_y + half_h\n return F.concat(xmin, ymin, xmax, ymax, dim=-1)\n\n\n# multiclass decoder\nclass ClassMDecoder(HybridBlock):\n\n def __init__(self, num_classes=None, thresh=0.01, from_sigmoid=False):\n super(ClassMDecoder, self).__init__()\n self._num_classes = num_classes\n self._thresh = thresh\n self._from_sigmoid = from_sigmoid\n\n def hybrid_forward(self, F, cls_preds):\n if not self._from_sigmoid:\n cls_preds = F.sigmoid(cls_preds, axis=-1)\n class_ids = F.argmax(cls_preds, axis=-1, keepdims=True)\n cls_preds = F.pick(cls_preds, class_ids, axis=-1, keepdims=True)\n\n # ex) thresh=0.01 이상인것만 뽑기\n mask = cls_preds > self._thresh\n class_ids = F.where(mask, class_ids, F.ones_like(class_ids) * -1)\n scores = F.where(mask, cls_preds, F.zeros_like(cls_preds))\n return class_ids, scores\n\n\n# multiclass per decoder\nclass ClassMPDecoder(HybridBlock):\n\n def __init__(self, num_classes=None, thresh=0.05, from_sigmoid=False):\n super(ClassMPDecoder, self).__init__()\n self._num_classes = num_classes\n self._thresh = thresh\n self._from_sigmoid = from_sigmoid\n\n def hybrid_forward(self, F, cls_preds):\n\n if not self._from_sigmoid:\n cls_preds = F.sigmoid(cls_preds)\n # batch x all feature number x foreground class(N) -> batch x all feature number x 1 - 클래스별로 쪼개기\n template = F.zeros_like(cls_preds.slice_axis(axis=-1, begin=0, end=1)) # batch x all feature number x 1\n class_ids = []\n # batch x all feature number x 1 당 번호 0부터 부여하기\n for i in range(self._num_classes):\n class_ids.append(template + i) # batch x all feature number x 1\n\n # batch x all feature number x foreground class 형태로 만들기\n class_ids = F.concat(*class_ids, dim=-1)\n\n # ex) thresh=0.05 이상인것만 뽑기\n mask = cls_preds > self._thresh\n class_ids = F.where(mask, class_ids, F.ones_like(class_ids) * -1)\n scores = F.where(mask, cls_preds, F.zeros_like(cls_preds))\n return class_ids, scores\n\n\n''' \n RetinaNet 논문을 읽고 구현해 봄\n 모든 박스를 decoding 할 필요는 없다. \n'''\n\n\nclass BoxDecodeLimit(HybridBlock):\n '''\n Parameters\n ----------\n decode_number : int / -1 : all\n '''\n\n def __init__(self, decode_number=1000):\n super(BoxDecodeLimit, self).__init__()\n self._decode_number = decode_number\n\n def hybrid_forward(self, F, box_preds, anchors, class_ids, class_scores):\n\n if self._decode_number > 0:\n cls_scores_argmax = F.argmax(class_scores, axis=-1) # (batch, all feature number)\n cls_scores_argsort = F.argsort(cls_scores_argmax, axis=1, is_ascend=False)\n cls_scores_argsort = F.slice_axis(cls_scores_argsort, axis=-1, begin=0,\n end=self._decode_number) # (batch, self._decode_number)\n class_ids = F.take(class_ids, cls_scores_argsort, axis=1)[0]\n class_scores = F.take(class_scores, cls_scores_argsort, axis=1)[0]\n box_preds = F.take(box_preds, cls_scores_argsort, axis=1)[0]\n anchors = F.take(anchors, cls_scores_argsort, axis=1)[0]\n return class_ids, class_scores, box_preds, anchors\n else:\n return class_ids, class_scores, box_preds, anchors\n\n\n# test\nif __name__ == \"__main__\":\n from core import RetinaNet, RetinaTrainTransform, DetectionDataset\n import os\n\n input_size = (512, 512)\n root = os.path.dirname(\n os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))\n transform = RetinaTrainTransform(input_size[0], input_size[1], make_target=False)\n dataset = DetectionDataset(path=os.path.join(root, 'Dataset', 'train'), transform=transform)\n num_classes = dataset.num_class\n\n image, label, _, _, _ = dataset[0]\n label = mx.nd.array(label)\n\n net = RetinaNet(version=18,\n input_size=input_size,\n anchor_sizes=[32, 64, 128, 256, 512],\n anchor_size_ratios=[1, pow(2, 1 / 3), pow(2, 2 / 3)],\n anchor_aspect_ratios=[0.5, 1, 2],\n num_classes=num_classes, # foreground만\n pretrained=False,\n pretrained_path=os.path.join(root, \"modelparam\"),\n anchor_box_offset=(0.5, 0.5),\n anchor_box_clip=True,\n ctx=mx.cpu())\n\n net.hybridize(active=True, static_alloc=True, static_shape=True)\n\n # batch 형태로 만들기\n image = image.expand_dims(axis=0)\n cls_preds, box_preds, anchors = net(image)\n\n boxdecoder = BoxDecoder(stds=(0.1, 0.1, 0.2, 0.2), means=(0., 0., 0., 0.))\n # classdecoder = ClassMDecoder(num_classes=num_classes, thresh=0.01, from_sigmoid=False)\n classdecoder = ClassMPDecoder(num_classes=num_classes, thresh=0.05, from_sigmoid=False)\n box_predictions = boxdecoder(box_preds, anchors)\n class_ids, class_scores = classdecoder(cls_preds)\n\n print(f\"class id shape : {class_ids.shape}\")\n print(f\"class scores shape : {class_scores.shape}\")\n print(f\"box predictions shape : {box_predictions.shape}\")\n '''\n class id shape : (1, 49104, 5)\n class scores shape : (1, 49104, 5)\n box predictions shape : (1, 49104, 4)\n '''\n","sub_path":"RETINA/core/utils/dataprocessing/predictFunction/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"231194712","text":"#!/usr/bin/env python\n\nimport CGIHTTPServer\nimport BaseHTTPServer\n\n# - - - for local testing - - -\n\nif __name__ == \"__main__\":\n server = BaseHTTPServer.HTTPServer\n handler = CGIHTTPServer.CGIHTTPRequestHandler\n server_address = (\"\", 8000)\n handler.cgi_directories = [\"/\"]\n httpd = server(server_address, handler)\n httpd.serve_forever()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"628789789","text":"#Funckije v pomoč:\n\ndef unikati(s):\n prazen_seznam = []\n\n for i in s: # for i in s pomeni, da se i premika po vrednostih seznama s, NE PO INDEKSIH!\n if i not in prazen_seznam:\n prazen_seznam.append(i)\n\n return prazen_seznam\n\ndef izloci_besedo(beseda):\n for i in beseda:\n if not beseda[0].isalnum():\n beseda = beseda[1:]\n else:\n break\n\n od_zadaj = len(beseda) - 1 #od_zadaj je stevec iz desne proti levi ki se premika po besedi, -1 ker se indeksiranje zacne z 0\n # in konca z eno manj kot je dejansko dolg niz\n while od_zadaj >= 0:\n if not beseda[od_zadaj].isalnum():\n beseda = beseda[:od_zadaj]\n else:\n break\n od_zadaj-=1\n\n return beseda\n\ndef se_zacne_z(tvit, c):\n prazen_seznam = []\n rezultat = []\n prazen_seznam = tvit.split(\" \")\n for s in prazen_seznam:\n if s[0] == c:\n rezultat.append(izloci_besedo(s))\n\n return rezultat\n\ndef zberi_se_zacne_z(tviti, c):\n rez = []\n for i in tviti:\n rez.extend(se_zacne_z(i,c)) # extend zdruzi dva seznama, ne uporabljaj \"append\"!!!\n\n return unikati(rez)\n\ndef vse_afne(tviti):\n return zberi_se_zacne_z(tviti, \"@\")\n\ndef vsi_hashtagi(tviti):\n return zberi_se_zacne_z(tviti, \"#\")\n\n############################\n\ndef get_tviti(tviti):\n seznam_tvitov = []\n for tvit in tviti:\n seznam_tvitov.append(tvit)\n\n return seznam_tvitov\n\n############################\n\ndef besedilo(tvit):\n razlom = tvit.split(\": \", 1)\n return razlom[1]\n\ndef avtor(tvit):\n razlom = tvit.split(\": \", 1)\n return razlom[0]\n\ndef zadnji_tvit(tviti):\n prazen_slovar = collections.defaultdict(str)\n\n for tvit in tviti:\n besedilo_tvita = besedilo(tvit)\n avtor_tvita = avtor(tvit)\n prazen_slovar[avtor_tvita] = besedilo_tvita\n\n return prazen_slovar\n\ndef prvi_tvit(tviti):\n prazen_slovar = collections.defaultdict(str)\n\n for tvit in tviti:\n besedilo_tvita = besedilo(tvit)\n avtor_tvita = avtor(tvit)\n\n if prazen_slovar[avtor_tvita] == \"\":\n prazen_slovar[avtor_tvita] = besedilo_tvita\n\n return prazen_slovar\n\ndef prestej_tvite(tviti):\n prazen_slovar = collections.defaultdict(int)\n\n for tvit in tviti:\n besedilo_tvita = besedilo(tvit)\n avtor_tvita = avtor(tvit)\n prazen_slovar[avtor_tvita] += 1\n\n return prazen_slovar\n\ndef omembe(tviti):\n prazen_slovar = collections.defaultdict(list)\n\n for tvit in tviti:\n avtor_tvita = avtor(tvit)\n prazen_slovar[avtor_tvita].extend(se_zacne_z(tvit, \"@\"))\n\n return prazen_slovar\n\ndef neomembe(ime, omembe):\n prazen_slovar = []\n for oseba, vrednost in omembe.items():\n if oseba not in omembe[ime] and oseba != ime:\n prazen_slovar.append(oseba)\n\n return prazen_slovar\n\ndef se_poznata(ime1, ime2, omembe):\n for oseba, vrednost in omembe.items():\n if oseba == ime1 and ime2 in vrednost:\n return True\n elif oseba == ime2 and ime1 in vrednost:\n return True\n\n return False\n\ndef hashtagi(tviti):\n prazen_slovar = collections.defaultdict(list)\n seznam_hashtagov = vsi_hashtagi(tviti)\n for hash in seznam_hashtagov:\n for tvit in tviti:\n for split in se_zacne_z(tvit, \"#\"):\n if split == hash:\n prazen_slovar[hash].append(avtor(tvit))\n\n for kljuc, vrednost in prazen_slovar.items():\n prazen_slovar[kljuc] = sorted(vrednost)\n\n return prazen_slovar\n\n\n","sub_path":"code/batch-1/vse-naloge-brez-testov/DN6-M-84.py","file_name":"DN6-M-84.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"510063930","text":"import sqlalchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Date, ForeignKey\nfrom sqlalchemy.orm import sessionmaker, relationship\n\nengine = create_engine(\"mysql+pymysql://brucy:brucy_getGoodJob@localhost/db_playground\", encoding='utf-8') # echo=True will print out detailed process\n\nBase = declarative_base() # generate orm base class\n\nclass Students(Base):\n __tablename__ = 'student'\n id = Column(Integer, primary_key = True)\n name = Column(String(32), nullable = False)\n register_date = Column(Date, nullable = False)\n\n def __repr__(self):\n return \"<%s name: %s>\" % (self.id, self.name)\n\n\nclass StudyRecord(Base):\n __tablename__ = 'study_record'\n id = Column(Integer, primary_key = True)\n day = Column(Integer, nullable = False)\n status = Column(String(32))\n stu_id = Column(Integer, ForeignKey('student.id'))\n\n student = relationship(\"Students\", backref = \"my_classes\")\n def __repr__(self):\n return \"<%s Day: %s Status: %s>\" % (self.student.name, self.day, self.status)\n\nBase.metadata.create_all(engine)\n\n###################### Insert Data #####################\nSession_class = sessionmaker(bind=engine) # create database dialog: session class, the return type of sessionmaker is class not instance\n\nSession = Session_class() # generate session instance, similar as cursor in pymysql\n\n# s1 = Students(name = \"Brucy\", register_date = '2017-05-26')\n# s2 = Students(name = \"Bella\", register_date = '2017-04-26')\n# s3 = Students(name = \"Bacon\", register_date = '2017-12-26')\n# s4 = Students(name = \"Cheese\", register_date = '2017-02-26')\n\n# study_obj1 = StudyRecord(day = 1, status = 'Yes', stu_id = 1)\n# study_obj2 = StudyRecord(day = 2, status = 'No', stu_id = 1)\n# study_obj3 = StudyRecord(day = 3, status = 'Yes', stu_id = 1)\n# Session.add_all([s1, s2, s3, s4, study_obj1, study_obj2, study_obj3])\n\nstu_obj = Session.query(Students).filter(Students.name == 'Brucy').first()\nprint(stu_obj.my_classes)\n\n# Session.commit()","sub_path":"PY_DB/sqlAlchemy_foreignKey.py","file_name":"sqlAlchemy_foreignKey.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"476900029","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport random\r\nfrom linebot.models import *\r\n\r\ndef spotify_random():\r\n\turl = 'https://spotifycharts.com/regional/'\r\n\twebContent = requests.get(url)\r\n\twebContent.encoding = 'UTF-8'\r\n\r\n\tsoup = BeautifulSoup(webContent.text, 'html.parser')\r\n\tresult = []\r\n\r\n\tsongList = soup.select('table.chart-table tbody tr')\r\n\trandom.shuffle(songList)\r\n\tfor song in songList[:10]:\r\n\t\tsongLink = song.select('td a')[0]['href']\r\n\t\twebContent = requests.get(songLink)\r\n\r\n\t\ttemp = song.select('td')[3]\r\n\t\tsongName = temp.select('strong')[0].text\r\n\t\tartist = temp.select('span')[0].text[3:]\r\n\t\talbumArtLink = song.select('td')[0].select('img')[0]['src'].replace('ab67616d00004851','ab67616d00001e02')\r\n\t\tresult.append(CarouselColumn(\r\n thumbnail_image_url=albumArtLink,\r\n title=artist,\r\n text=songName,\r\n actions=[\r\n \tURIAction(\r\n\t\t\t\t\t\tlabel='Open on Spotify',\r\n\t\t\t\t\t\turi=songLink\r\n\t\t\t\t\t),\r\n\t\t\t\t\tMessageAction(\r\n\t\t\t\t\t\tlabel='顯示歌手與歌名',\r\n\t\t\t\t\t\ttext='{} by {}'.format(songName,artist)\r\n\t\t\t\t\t)\r\n ]\r\n \t)\r\n )\r\n\r\n\treturn result\r\n\r\nif __name__ == '__main__':\r\n\tprint(spotify_random())","sub_path":"function/spotify_top_200.py","file_name":"spotify_top_200.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"406646011","text":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import Embedding\nfrom keras.layers import LSTM\nfrom keras.preprocessing import sequence\nfrom keras.models import load_model\nimport numpy as np\nimport gensim\nimport pickle\n\nmodel = gensim.models.Word2Vec.load(\"model\")\nlstm_model = load_model('lstm.h5')\n\nresearcher_sentences = []\nsupporter_sentences = []\npurchaser_sentences = []\n\nsentences = []\n\nf = open('Test.txt', 'r')\nlines = f.readlines()\nlines_count = len(lines)\nright_count = 0\nwrong_count = 0\nX = []\nY = []\nY_test = []\nfor line in lines:\n line = line[:-1]\n sentence = line.split(\"\\t\")\n\n if sentence[-1] == \"0\":\n researcher_sentences.append(sentence)\n elif sentence[-1] == \"1\":\n supporter_sentences.append(sentence)\n elif sentence[-1] == \"2\":\n purchaser_sentences.append(sentence)\n\n sentences.append(sentence)\n\n vectors = []\n urls = sentence[:-1]\n url_count = len(urls)\n # print(\"url_count:%s\" % url_count)\n if url_count == 0:\n continue\n for url in urls:\n vectors.append(model[url])\n X.append(vectors)\n\n label = -1\n if sentence[-1] == \"0\":\n label = 0\n elif sentence[-1] == \"1\":\n label = 1\n elif sentence[-1] == \"2\":\n label = 2\n else:\n print(\"wrong\")\n Y.append(label)\n\n label1 = [0,0,0]\n if sentence[-1] == \"0\":\n label1 = [1,0,0]\n elif sentence[-1] == \"1\":\n label1 = [0,1,0]\n elif sentence[-1] == \"2\":\n label1 = [0,0,1]\n else:\n print(\"wrong\")\n Y_test.append(label1)\n # print(\"sum:%s\" % vector)\n # print(\"divide:%s\" % vector)\n # prediction = clf.predict(vector)\n # # print(prediction[0])\n # # print(sentence[-1])\n # if prediction[0] == sentence[-1]:\n # right_count += 1\n\nY_test.append(Y_test[0])\nY_test.append(Y_test[0])\nY_test.append(Y_test[0])\nY_test.append(Y_test[0])\nX.append(X[0])\nX.append(X[0])\nX.append(X[0])\nX.append(X[0])\nX_test = sequence.pad_sequences(X, maxlen=552)\nPx = lstm_model.predict(X_test)\nPx = Px[:-4]\n\nfor i, p in enumerate(Px):\n p_index = np.argmax(p)\n label = Y[i]\n if p_index == label:\n right_count += 1\n else:\n wrong_count += 1\n print(\"wrong:%s,p:%s,l:%s\" % (wrong_count,p_index,label))\n\nrecall_purchaser_count = 0\nprecision_purchaser_count = 0\nright_precision_purchaser_count = 0\nrecall_supporter_count = 0\nprecision_supporter_count = 0\nright_precision_supporter_count = 0\nrecall_researcher_count = 0\nprecision_researcher_count = 0\nright_precision_researcher_count = 0\nfor i, y in enumerate(Y[:-4]):\n # print(prediction[0])\n # print(sentence[-1])\n\n p_index = np.argmax(Px[i])\n if p_index == 0:\n precision_researcher_count += 1\n if y == 0:\n right_precision_researcher_count += 1\n\n if p_index == 1:\n precision_supporter_count += 1\n if y == 1:\n right_precision_supporter_count += 1\n\n if p_index == 2:\n precision_purchaser_count += 1\n if y == 2:\n right_precision_purchaser_count += 1\n \nscore = lstm_model.evaluate(X_test, Y_test, batch_size=32)\n\nprint(\"score:%s\" % score)\n\nprint(\"general:%s/%s\" % (right_count,len(Px)))\n\nprint(\"purchaser######\")\nprint(\"recall:%s/%s\" % (right_precision_purchaser_count,len(purchaser_sentences)))\nprint(\"precision:%s/%s\" % (right_precision_purchaser_count,precision_purchaser_count))\n\nprint(\"supporter######\")\nprint(\"recall:%s/%s\" % (right_precision_supporter_count,len(supporter_sentences)))\nprint(\"precision:%s/%s\" % (right_precision_supporter_count,precision_supporter_count))\n\nprint(\"researcher######\")\nprint(\"recall:%s/%s\" % (right_precision_researcher_count,len(researcher_sentences)))\nprint(\"precision:%s/%s\" % (right_precision_researcher_count,precision_researcher_count))\n\n\n# general:891/1256=73.7261146%\n# purchaser######\n# recall:73/228=31.578947368%\n# precision:73/179=51.428571429%\n# supporter######\n# recall:577/657=89.193302892%\n# precision:577/659=88.922610015%\n# researcher######\n# recall:241/371=74.393530997%\n# precision:241/406=62.02247191%","sub_path":"4.model-testing/lstmtest.py","file_name":"lstmtest.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"101290065","text":"import pandas as pd\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\nimport numpy as np\nfrom datetime import datetime\n\n\ndef conv_perc(x):\n xv = x\n if \"%\" in str(xv):\n xv = int(re.sub(\"[^\\d+]+\", \"\", xv))/100\n val = xv\n elif str(xv) == \"?\":\n val = np.nan\n else:\n val = x\n return val\n\n\ndef date_col(x, i):\n try:\n datestring = re.findall(\"(\\d+)\", str(x))\n mlist = re.findall(\"([a-zA-z]+)\", x)\n if len(mlist) > 1:\n if i == 1:\n month = mlist[0]\n if i == 2:\n month = mlist[-1]\n if len(mlist) == 1:\n month = mlist[0]\n if i == 1:\n date = datestring[0]\n if i == 2 and len(datestring) == 1:\n date = datestring[0]\n if i == 2 and len(datestring) > 1:\n date = datestring[1]\n ds = str(date) + \"_\" + month + \"_2021\"\n ds_f = datetime.strptime(ds, \"%d_%b_%Y\")\n return(f\"{ds_f.day}/{ds_f.month}/{ds_f.year}\")\n except:\n return np.nan\n\n\ndef cycle_table(table):\n #Initiate table\n constructeddf = pd.read_html(table.get_attribute(\"outerHTML\"), header=0, skiprows=[1])[0]\n\n #Create Columns\n constructeddf[\"Crosstab\"] = np.nan\n constructeddf[\"url\"] = np.nan\n\n #Compile Regex\n ftype = re.compile(\"((\\.pdf)|(\\.xlsx))$\", re.MULTILINE)\n perc_re = re.compile(\"(?<=%)(.*?)(?=%)\", re.DOTALL)\n split = re.compile(\"(.+(?=on))|(\\d+)\")\n\n #Find Rows\n rows = table.find_elements_by_xpath(\".//tr\")\n\n #Other\n rowindex = 0\n\n #Cycler\n for row in rows:\n cells = row.find_elements_by_xpath(\".//td\")\n if len(cells) == 0:\n continue\n i = 1\n for cell in cells:\n if (i == 1):\n inner_text = cell.get_attribute(\"innerHTML\")\n soup = BeautifulSoup(inner_text, features=\"lxml\")\n if soup.get_text() == \"\":\n break\n url = cell.find_element_by_xpath(\".//a\").get_attribute(\"href\")\n constructeddf.loc[rowindex, [\"url\"]] = str(url)\n crosstab = re.search(ftype, url)\n if crosstab != None:\n constructeddf.loc[rowindex, [\"Crosstab\"]] = \"Crosstab\"\n\n if i == 11: #Expand table\n text = cell.get_attribute(\"innerHTML\")\n soup = BeautifulSoup(text, features=\"lxml\")\n finds = re.findall(perc_re, soup.get_text())\n if len(finds) > 0:\n for find in finds:\n vals = re.findall(split, find)\n party = vals[0][0].strip()\n perc = vals[1][1].strip()\n if party in constructeddf.columns:\n constructeddf.loc[rowindex, [party]] = int(perc)/100\n else:\n constructeddf[party] = np.nan\n constructeddf.loc[rowindex, [party]] = int(perc)/100\n i += 1\n rowindex += 1\n return constructeddf\n\n\nif __name__ == \"__main__\":\n\n print(\"Scraping polls...\")\n #Set Chrome Options\n opts = Options()\n opts.add_argument(\"--disable-extensions\")\n opts.add_argument(\"--disable-gpu\")\n opts.add_argument(\"--headless\")\n\n #Initiate Chrome\n driver = webdriver.Chrome(\"/mnt/sda1/chromedriver\", options=opts)\n print(\"Chrome initiated, scraping table\")\n # Once Chrome is started, ensure closure on error\n try:\n # Get table\n driver.get(\"https://en.wikipedia.org/wiki/Opinion_polling_for_the_next_United_Kingdom_general_election\")\n table = driver.find_element_by_xpath(\"//h3[contains(.,'2021')]/..//table//th[contains(.,'Pollster')]/../../..\")\n\n #Cycle\n constructeddf = cycle_table(table)\n driver.quit()\n\n except Exception as e:\n print(e)\n driver.quit()\n\n print(\"Table retrieved\")\n #Final Wrangles\n\n #Get rid of non-rows\n constructeddf = constructeddf[constructeddf['url'].notna()]\n\n #Convert dateranges\n constructeddf[\"StartDate\"] = constructeddf.apply(lambda x: date_col(x[\"Datesconducted\"], 1), axis=1)\n constructeddf[\"EndDate\"] = constructeddf.apply(lambda x: date_col(x[\"Datesconducted\"], 2), axis=1)\n\n #Convert percs to ints\n constructeddf = constructeddf.applymap(conv_perc)\n\n #Cosmetic stuff\n constructeddf = constructeddf.drop([\"Datesconducted\"], axis=1)\n constructeddf.rename(columns={'Others': 'Minor'}, inplace=True)\n constructeddf = constructeddf[['StartDate', 'EndDate'] + [c for c in constructeddf if c not in ['StartDate', 'EndDate']]]\n\n\n #Push polls\n constructeddf.to_csv(\"polls.csv\", index=False)\n print(\"Polls Built\")","sub_path":"Poll_tracker_model/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"628147198","text":"# Sertis Face Regconigtion Croping Coding Date 10/11/2020 By Panupong Suksuwan\n\"\"\"\nนำเข้า Lib ที่ใช้งาน \n- Numpy ไว้จัดการ Array จากการภาพเช่น Copy Image Array \n- cv2(OpenCV) Pre-trained Model สำหรับตวรจจับใบน้าโดยจะใช้ส่วนของ haarcascade_frontalcatface.xml \n- mathplotlib สำหรับการ plot กรอบใบหน้าบนภาพ\n- อาจจะมีเพิ่มเติมเช่ม os Path File หรือ Flask\n\"\"\"\nfrom flask import Flask, request\nfrom flask_cors import CORS,cross_origin\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalcatface.xml')\n\n# นำเข้ารูปสำหรับการทำ Face Regconigtion Croping\nimage = cv2.imread('download.jpg')\n\n# สำรองภาพสีไว้สำหรับผลลัพธ์\nraw = np.copy(image)\n\n# แปลงภาพให้เป็นโทนสี RGB\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# สำรองภาพที่เป็นโทนสี RGB\nimage_copy = np.copy(image)\n\n# แปลงภาพให้เป็นโทนสี RGB เป็น Grayscale\ngray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\n# ใช้ Pre-trained Model ในการ Dectect หน้า\nfaces = face_cascade.detectMultiScale(raw, 1.25, 6)\n\n# แสดงค่าจำนวนหน้าที่ Pre-trained Model พบ บนหน้า Console\nprint('Number of faces detected:', len(faces))\n\n# สร้างกรอบบนหน้าที่ Dectect เจอ\nface_crop = []\nfor f in faces:\n x, y, w, h = [ v for v in f ]\n cv2.rectangle(image_copy, (x,y), (x+w, y+h), (255,0,0), 3)\n\n # Crop ตามกรอบที่ Plot\n face_crop.append(raw[y:y+h, x:x+w])\n\nfor face in face_crop:\n cv2.imshow('face',face)\n cv2.waitKey(0)\n\n# Display the face crops With Gui\nfig = plt.figure(figsize = (9,9))\naxl = fig.add_subplot(111)\naxl.set_xticks([])\naxl.set_yticks([])\naxl.set_title(\"Largest Face Immage Cropped\")\n\n# จุด Return File\nfilename = 'Result.jpg'\ncv2.imwrite(filename, face)\n","sub_path":"Largest_Face_Crop.py","file_name":"Largest_Face_Crop.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"643362079","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport sys\nimport geograpy\nimport collections\nfrom geograpy import extraction\nfrom geotext import GeoText\nimport re\nfrom time import strptime\nfrom llr import utils as llrutils \n\n#Added from https://gist.github.com/onyxfish/322906#gistcomment-1701799\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\ndef flatten(l):\n for el in l:\n if isinstance(el, collections.Iterable) and not isinstance(el, basestring):\n for sub in flatten(el):\n yield sub\n else:\n yield el\n \ndef getPlaceET_fromText_NLTK(text):\n result = list()\n if not text:\n return filter(None, result) \n\n # You can now access all of the places found by the Extractor\n places = geograpy.get_place_context(text=text) \n for place in (places.countries + places.other): \n c = llrutils.getISO3166_1code(place)\n if not c:\n c = llrutils.getUNM49code(place)\n result.append(c)\n return filter(None, flatten(result))\n \ndef getPlaceET_fromText_GeoText(text):\n result = list()\n if not text:\n return filter(None, result) \n\n places = GeoText(text)\n \n for place in (places.countries):\n c = llrutils.getISO3166_1code(place)\n if not c:\n c = llrutils.getUNM49code(place)\n result.append(c)\n return filter(None, flatten(result))\n\ndef getLPOAC(label):\n return {\n \"Economic Growth\" : None,\n \"Governance, Conflict, and Humanitarian Assistance\" : None,\n \"Climate Change and Natural Resource Management\" : \"Land Use, Management & Investment\",\n \"Food Security\" : None,\n \"Gender Equality and Women's Empowerment\" : \"Access to Land & Tenure Security\",\n \"Responsible Land Based Investment\" : \"Land Use, Management & Investment\",\n \"Customary and Community Tenure\" : \"Access to Land & Tenure Security\",\n \"Marine Tenure and Coastal Resource Management\" : \"Land Use, Management & Investment\",\n \"Sustainable Urbanization\" : None\n }.get(label, None)\n\ndef getLPTheme(label):\n return {\n \"Economic Growth\" : \"Socio-Economic & Institutional Context\",\n \"Governance, Conflict, and Humanitarian Assistance\" : \"Land Conflicts\",\n \"Climate Change and Natural Resource Management\" : \"Land, Climate change & Environment\",\n \"Food Security\" : \"Land & Food Security\",\n \"Gender Equality and Women's Empowerment\" : \"Land & Gender\",\n \"Responsible Land Based Investment\" : \"Land & Investments\",\n \"Customary and Community Tenure\" : \"Indigenous & Community Land Rights\",\n \"Marine Tenure and Coastal Resource Management\" : None,\n \"Sustainable Urbanization\" : \"Urban Tenure\"\n }.get(label, None)\n\ndef getLPConcepts(label):\n return {\n \"Economic Growth\" : [\"development\", \"sustainable development\"],\n \"Governance, Conflict, and Humanitarian Assistance\" : [\"land conflicts\", \"land governance\"],\n \"Climate Change and Natural Resource Management\" : [\"climate change\", \"environment\", \"natural resources management\", \"sustainable land management\"],\n \"Food Security\" : [\"food security\"], \n \"Gender Equality and Women's Empowerment\" : [\"gender equity in access to land\", \"women\"], \n \"Responsible Land Based Investment\" : [\"land investments\"],\n \"Customary and Community Tenure\" : [\"customary tenure\", \"customary land rights\", \"local community\", \"community land rights\"],\n \"Marine Tenure and Coastal Resource Management\" : [\"coastal area\", \"land management\", \"sustainable land management\", \"land tenure systems\"],\n \"Sustainable Urbanization\" : [\"urban areas\", \"land development (urbanization)\", \"urbanization\", \"sustainable development\"]\n }.get(label, None)\n\ndef getPublisher(label):\n label_lower= label.lower()\n if \"flacso\" in label_lower and (\"quito\" in label_lower or \"ecuador\" in label_lower):\n label = \"Facultad Latinoamericana de Ciencias Sociales Ecuador\"\n\n if \"flacso\" in label_lower and (\"chile\" in label_lower):\n label = \"Facultad Latinoamericana de Ciencias Sociales Chile\"\n \n if \"flacso\" in label_lower and (\"argentina\" in label_lower):\n label = \"Facultad Latinoamericana de Ciencias Sociales Argentina\"\n \n if \"flacso\" in label_lower and (u\"méxico\" in label_lower):\n label = u\"Facultad Latinoamericana de Ciencias Sociales México\"\n\n if \"Colegio de Postgraduados\" in label:\n label = \"Colegio de Postgraduados\"\n\n if (\"Universidad de Buenos Aires\" in label) or (u\"Facultad de Ciencias Económicas, UBA\" in label):\n label = \"Universidad de Buenos Aires\"\n \n if \"Universidad Austral de Chile\" in label:\n label = \"Universidad Austral de Chile\"\n \n if u\"Universidad Andina Simón Bolívar\" in label:\n label = u\"Universidad Andina Simón Bolívar\"\n \n if u\"Pontificia Universidad Católica de Chile\" in label:\n label = u\"Pontificia Universidad Católica de Chile\"\n \n if (u\"UASLP\" in label) or (u\"Universidad Autónoma de San Luis Potosí\" in label):\n label = u\"Universidad Autónoma de San Luis Potosí\"\n \n if u\"Universidad Católica del Norte\" in label:\n label = u\"Universidad Católica del Norte\"\n \n if u\"Universidad del Pacífico\" in label:\n label = u\"Universidad del Pacífico\"\n \n if u\"Universidad Nacional de Cuyo\" in label:\n label = u\"Universidad Nacional de Cuyo\"\n \n if u\"Universidad del Rosario\" in label:\n label = u\"Universidad del Rosario\"\n \n if u\"CAAP\" in label:\n label = u\"Centro Andino de Acción Popular\"\n\n if u\"Universidad Nacional de Quilmes\" in label:\n label = u\"Universidad Nacional de Quilmes\"\n \n if u\"EAFIT\" in label:\n label = u\"Universidad EAFIT\"\n \n if u\"Universidad del Rosario\" in label:\n label = u\"Universidad del Rosario\"\n \n if (u\"Universidad Nacional de la Amazonia Peruana\" in label) or (u\"Universidad Nacional de la Amazonía Peruana\" in label) or (u\"Universidad de la Amazonía Peruana\" in label):\n label = u\"Universidad Nacional de la Amazonía Peruana\"\n \n if u\"Universidad de Lima\" in label:\n label = u\"Universidad de Lima\"\n \n if u\"UAEMEX\" in label:\n label = u\"Universidad Autónoma del Estado de México\"\n\n if (u\"Pontificia Universidad Javeriana\" in label) or (u\"Facultad de Estudios Ambientales y Rurales\" in label):\n label = u\"Pontificia Universidad Javeriana\"\n \n if u\"Universidad Nacional (Costa Rica)\" in label:\n label = u\"Universidad Nacional de Costa Rica\"\n\n if u\"Universidad Sergio Arboleda\" in label:\n label = u\"Universidad Sergio Arboleda\"\n \n\n#CLEAN \n if u\"Maestría en\" in label:\n label = None\n elif \"Facultad\" in label and (u\"Facultad Latinoamericana de Ciencias Sociales\" not in label):\n label = None\n elif \"Escuela de\" in label:\n label = None\n \n return {\n \"University of Costa Rica\" : \"Universidad de Costa Rica\",\n \"Costa Rica University\" : \"Universidad de Costa Rica\",\n \"Agenda Ambiental\": None,\n u\"Perú\": None,\n \"Humanidades y Ciencias Sociales\": None\n\n }.get(label, label)\n\n\n\n# Target: 2011-12-13 (YYYY-MM-DD) (Drupal)\n\ndef clean_date (date):\n \n dateArray = date.strip().lower().split(\"-\")\n \n if len(dateArray) == 1: #YYYY\n pattern_YYYY = re.compile(\"^[0-9]{4}$\") #YYYY\n if re.search(pattern_YYYY, date):\n date = date+\"-12-31\"\n\n if len(dateArray) == 2:\n year = dateArray[0]\n month = dateArray[1]\n if month in [\"01\",\"03\",\"05\", \"07\", \"08\", \"10\", \"12\"]:\n date = year+\"-\"+month+\"-31\"\n elif month in [\"02\"]:\n date = year+\"-\"+month+\"-28\"\n else:\n date = year+\"-\"+month+\"-30\"\n \n if len(dateArray) == 3:\n year = dateArray[0]\n month = dateArray[1]\n day = dateArray[2].split(\"-\")[0] \n date = year+\"-\"+month+\"-\"+day\n \n return date\n\ndef getLLR_type(label):\n return {\n \"article\": \"Journal Articles & Books\",\n \"report\": \"Reports & Research\",\n \"masterThesis\": \"Reports & Research\", \n \"doctoralThesis\": \"Reports & Research\"\n }[label]","sub_path":"landlibrary/importers/LAReferencia/python-scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"355254221","text":"\"\"\"Heuristics for Best First Search.\"\"\"\nfrom abc import ABC, abstractmethod\nfrom typing import List\nimport numpy as np\nimport networkx as nx\nfrom utils import println\nimport copy\n\n\ndef manha_dist(a, b):\n \"\"\"Measure Manhattan distance.\"\"\"\n (x1, y1) = a\n (x2, y2) = b\n return abs(x1 - x2) + abs(y1 - y2)\n\n\nclass Heuristics(ABC):\n \"\"\"Class for defining heuristics.\"\"\"\n\n @abstractmethod\n def __call__(self, states: List):\n \"\"\"Call method, compute `heuristics` of List `states`.\"\"\"\n return\n\n\nclass EasyRule(Heuristics):\n \"\"\"Simple heuristics.\n\n Computes Manhattan distance for:\n * Boxes to goals.\n * Agents to boxes.\n \"\"\"\n\n def __call__(self, states: List):\n \"\"\"Calculate heuristic for states in place.\"\"\"\n if type(states) is not list:\n states = [states]\n if len(states) == 0:\n return None\n\n for state in states:\n box_goal_cost = 0\n agt_box_cost = 0\n agt_box_costs = []\n for key in state.getGoalKeys():\n goal_params = state.getGoalsByKey(key)\n box_params = state.getBoxesByKey(key)\n # maybe add some temporary costs here for each key\n\n # find every position of goals and boxes with the given key\n for goal_pos, goal_color in goal_params:\n box_goal_costs = []\n for box_pos, _ in box_params:\n # only take agents with the same color as goalColor\n if goal_color in state.agentColor:\n agent_keys = state.getAgentsByColor(goal_color)\n\n if manha_dist(goal_pos, box_pos) == 0:\n continue\n\n for agent_key in agent_keys:\n agentPos = state.getAgentsByKey(agent_key)[0][0]\n agt_box_costs.append(manha_dist(agentPos, box_pos))\n\n box_goal_costs.append(manha_dist(box_pos, goal_pos))\n\n if len(box_goal_costs) > 0:\n box_goal_cost += min(box_goal_costs)\n if len(agt_box_costs) > 0:\n agt_box_cost += sum(agt_box_costs)\n\n state.h = box_goal_cost + agt_box_cost\n state.f = state.h * 5 + state.g\n\n\nclass WeightedRule(Heuristics):\n \"\"\"Weighted heuristics.\n\n The distance from a box to a box is weigthed more (used for communication).\n Computes Manhattan distance for:\n * Boxes to goals.\n * Agents to boxes.\n \"\"\"\n\n def __init__(self, weight: str):\n \"\"\"Initialize object with state and `string` of box to weight more.\"\"\"\n self.weight = weight\n\n def __call__(self, states: List):\n \"\"\"Calculate heuristic for states in place.\"\"\"\n if type(states) is not list:\n states = [states]\n if len(states) == 0:\n return None\n\n for state in states:\n box_goal_cost = 0\n agt_box_cost = 0\n agt_box_costs = []\n for key in state.getGoalKeys():\n goal_params = state.getGoalsByKey(key)\n box_params = state.getBoxesByKey(key)\n # maybe add some temporary costs here for each key\n\n # find every position of goals and boxes with the given key\n for goal_pos, goal_color in goal_params:\n box_goal_costs = []\n for box_pos, _ in box_params:\n # only take agents with the same color as goalColor\n agent_keys = state.getAgentsByColor(goal_color)\n\n if manha_dist(goal_pos, box_pos) == 0:\n continue\n\n for agent_key in agent_keys:\n agentPos = state.getAgentsByKey(agent_key)[0][0]\n agt_box_costs.append(manha_dist(agentPos, box_pos))\n\n box_goal_costs.append(manha_dist(box_pos, goal_pos))\n\n if len(box_goal_costs) > 0:\n box_cost = min(box_goal_costs)\n if key.lower() == self.weight:\n box_cost *= 10\n box_goal_cost += box_cost\n if len(agt_box_costs) > 0:\n agt_box_cost += sum(agt_box_costs)\n\n state.h = box_goal_cost + agt_box_cost\n state.f = state.h * 5 + state.g\n\n\nclass GoAway(Heuristics):\n \"\"\"GoAway heuristics.\n\n The distance from a box to a box is weigthed more (used for communication).\n Computes Manhattan distance for:\n * Boxes to goals.\n * Agents to boxes.\n \"\"\"\n\n def __call__(self, states: List):\n \"\"\"Calculate heuristic for states in place.\"\"\"\n if type(states) is not list:\n states = [states]\n if len(states) == 0:\n return None\n\n for state in states:\n box_goal_cost = 0\n agt_box_cost = 0\n agt_box_costs = []\n for key in state.getGoalKeys():\n goal_params = state.getGoalsByKey(key)\n box_params = state.getBoxesByKey(key)\n # maybe add some temporary costs here for each key\n\n # find every position of goals and boxes with the given key\n for goal_pos, goal_color in goal_params:\n box_goal_costs = []\n for box_pos, _ in box_params:\n # only take agents with the same color as goalColor\n agent_keys = state.agents.keys()\n\n if manha_dist(goal_pos, box_pos) == 0:\n continue\n\n for agent_key in agent_keys:\n agentPos = state.getAgentsByKey(agent_key)[0][0]\n agt_box_costs.append(-10 * manha_dist(agentPos, box_pos))\n\n box_goal_costs.append(manha_dist(box_pos, goal_pos))\n\n box_goal_cost += min(box_goal_costs)\n if len(agt_box_costs) > 0:\n agt_box_cost += sum(agt_box_costs)\n\n state.h = box_goal_cost + agt_box_cost\n state.f = state.h * 25\n\n\nclass dGraph(Heuristics):\n def __init__(self, state: np.array):\n \"\"\"Initialize object by building the VIS(V,E) graph.\"\"\"\n self.dirs = [\n np.array([0, 1]),\n np.array([1, 0]),\n np.array([0, -1]),\n np.array([-1, 0]),\n np.array([0, 1]),\n np.array([1, 0]),\n np.array([0, -1]),\n np.array([-1, 0]),\n ]\n # self.weight = weight\n self.cornerSet = []\n self.map = state.map\n self.uniqueCorners = set()\n self.poses = []\n self.graph = self.build_graph(state.map)\n self.boxes = {}\n\n # self.dir = {\"N\": (-1, 0), \"E\": (0, 1), \"S\": (1, 0), \"W\": (0, -1)}\n\n def build_graph(self, map: np.array) -> List:\n explored = set()\n\n # add boundry wall\n rows, cols = map.shape\n for col in range(0, cols):\n explored.add(tuple([0, col]))\n explored.add(tuple([rows - 1, col]))\n for row in range(0, rows):\n explored.add(tuple([row, 0]))\n # explored.add(tuple(np.array([row, cols - 1])))\n\n # find contours\n self.cornerSets = []\n println(explored)\n for col in range(1, cols):\n for row in range(1, rows):\n pos = np.array([row, col])\n if map[row, col] == \"+\":\n freePos = np.array([row, col - 1])\n # println(freePos, tuple(freePos) in explored)\n if map[row, col - 1] != \"+\" and tuple(pos) not in explored:\n # println(\"first spot\", freePos)\n corners = self.findEdges(freePos, map, explored)\n if corners:\n self.cornerSets.append(corners)\n\n G = self.generateGraph(copy.deepcopy(map))\n return G\n\n def draw(self, G):\n import matplotlib.pyplot as plt\n\n elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d[\"weight\"] > 0.5]\n esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d[\"weight\"] <= 0.5]\n pos = nx.spring_layout(G)\n nx.draw_networkx_nodes(G, pos, node_size=700)\n nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6)\n nx.draw_networkx_edges(\n G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color=\"b\", style=\"dashed\"\n )\n\n nx.draw_networkx_labels(G, pos, font_size=20, font_family=\"sans-serif\")\n\n plt.show()\n\n def generateGraph(self, map):\n cornerSets = self.cornerSets\n for corners in cornerSets:\n println(\"corner set\", corners)\n if type(corners) != list:\n corners = [corners]\n for corner in corners:\n self.uniqueCorners.add(corner)\n map[corner] = \"O\"\n println(map)\n\n self.uniqueCorners = list(self.uniqueCorners)\n\n # TODO fix order of corners\n # cornerSets[0] = cornerSets[0][-1::] + cornerSets[0][:-1:]\n\n G = nx.DiGraph()\n\n println(cornerSets)\n # for corner in self.uniqueCorners:\n # G.add_node(tuple(corner), pos=corner)\n\n for corners in cornerSets:\n # First position is always at the end\n for i in range(len(corners)):\n # println(corners[i - 1], corners[i])\n if not np.array_equal(corners[i - 1], corners[i]):\n if self.getValidKeypoint(map, corners[i - 1], corners[i], []) is True:\n\n corner1 = corners[i - 1]\n corner2 = corners[i]\n dist = manha_dist(\n (corner1[0], corner1[1]), (corner2[0], corner2[1])\n )\n println(corner1, corner2, dist)\n G.add_edge(corner1, corner2, weight=dist)\n G.add_edge(corner2, corner1, weight=dist)\n\n for corner1 in self.uniqueCorners:\n #G.add_node(tuple(corner), pos=corner)\n closestCorners = self.connectCornerSets(corner1, 4, 0.5)\n #println(corner1, closestCorners)\n for corner2 in closestCorners:\n dist = manha_dist((corner1[0], corner1[1]), (corner2[0], corner2[1]))\n G.add_edge(corner1, corner2, weight=dist)\n\n # if len(cornerSets) > 1:\n # raise Exception(\"####### No edge fusion implemented yet\")\n\n # println(cornerSets)\n # self.draw(G)\n\n # import sys; sys.exit()\n\n # for corners in cornerSets:\n # for i in range(len(corners) - 1):\n # if not np.array_equal(corners[i], corners[i + 1]):\n # corner1 = corners[i]\n # corner2 = corners[i + 1]\n # dist = manha_dist(\n # (corner1[0], corner1[1]), (corner2[0], corner2[1])\n # )\n # println(corner1, corner2, dist)\n # G.add_edge(corner1, corner2, weight=dist)\n # G.add_edge(corner2, corner1, weight=dist)\n # pass\n del map\n return G\n\n def checkAndAddCorner(self, map, corners, cornerPos):\n if map[tuple(cornerPos)] == \"+\":\n return False\n corners.append(tuple(cornerPos))\n return True\n\n def addCorner(self, map, newPos, pos, dir, prevDir, explored, corners):\n if map[tuple(newPos)] != \"+\" and tuple(newPos) not in explored:\n # tempExplored.add(tuple(newPos))\n cornerType = dir - prevDir\n if cornerType == -1:\n # println(pos, cornerType)\n self.checkAndAddCorner(map, corners, pos)\n\n # println(\"moving here:\", (newPos, prevDir, dir))\n return True\n elif map[tuple(newPos)] == \"+\":\n # println(\"wall added\", tuple(newPos))\n explored.add(tuple(newPos))\n return False\n\n def connectCornerSets(self, pos, points, percent=1):\n map = self.map\n corners = np.asarray(self.uniqueCorners)\n sortedKp = sorted(corners, key=lambda kp: np.linalg.norm(pos - kp, 1))\n validKps = []\n for i, kp in enumerate(sortedKp):\n if kp[0] != pos[0] or kp[1] != pos[1]:\n self.getValidKeypoint(map, pos, kp, validKps)\n if len(validKps) >= points:\n break\n if i > percent * len(sortedKp):\n break\n return list(validKps) # sort by age\n\n # return sorted(corners, key=lambda p: p)\n\n\n def findEdges(self, initPos, map, explored):\n dir = -1\n prevDir = dir + 1\n pos = initPos\n corners = []\n initDir = -999\n newPos = None\n isDone = False\n # TODO add a new corner here probably\n while not isDone:\n for j in range(0, 4):\n dir = dir + 1\n newPos = pos + self.dirs[dir]\n if self.addCorner(map, newPos, pos, dir, prevDir, explored, corners):\n prevDir = dir % 4 # 4 directions\n if np.array_equal(initPos, pos) and prevDir == initDir:\n isDone = True\n pos = newPos\n if initDir == -999:\n initDir = prevDir\n break\n dir = prevDir - 2\n\n return corners\n\n def getValidKeypoint(self, map, pos, kp, validKps):\n\n tempPos = np.array(pos)\n # println(\"keypoint:\", kp, pos)\n diff = np.array(tempPos) - kp\n dir = [0, 0]\n if diff[0] < 0:\n dir[0] = 1\n else:\n dir[0] = -1\n\n while tempPos[0] != kp[0]:\n tempPos[0] += dir[0]\n # print(tempPos)\n if map[tuple(tempPos)] == \"+\":\n return None\n elif tuple(tempPos) in validKps:\n return tempPos\n\n\n if diff[1] < 0:\n dir[1] = 1\n else:\n dir[1] = -1\n\n while tempPos[1] != kp[1]:\n tempPos[1] += dir[1]\n # println(tempPos)\n if map[tuple(tempPos)] == \"+\" or tuple(tempPos) in validKps:\n return None\n elif tuple(tempPos) in validKps:\n return tempPos\n\n # TODO, if it passes a corner point skip to next\n\n # println(\"best keypoint for pos\", pos,\"is:\", kp)\n validKps.append(tuple(kp))\n return True\n # return kp\n\n def findBestKeyPoint(self, pos, pos2):\n # TODO optimize this!\n # By nature of how the corners are generated the nearst point, if reachable\n # will always be reachable from all directions minimizing the distance\n # between the pos and keypoint\n map = self.map\n corners = np.asarray(self.uniqueCorners)\n # println(list([np.linalg.norm(pos - kp, 1), kp] for kp in corners))\n sortedKp = sorted(corners, key=lambda kp: np.linalg.norm(pos - kp, 1))\n # println(pos)\n validKps = []\n for kp in sortedKp:\n\n self.getValidKeypoint(map, pos, kp, validKps)\n if len(validKps) >= 4:\n break\n if not validKps:\n return [pos2]\n # println(validKps)\n if np.linalg.norm(np.asarray(validKps[0]) - np.asarray(pos)) >= np.linalg.norm(\n np.asarray(pos) - np.asarray(pos2)\n ):\n self.getValidKeypoint(map, pos, pos2, validKps)\n # println(validKps)\n\n return list(validKps) # sort by age\n\n # return sorted(corners, key=lambda p: p)\n\n def findPathPart(self, state, pathId, combId):\n # (State, pathIndex)\n # TODO when calculating new dijkstras maybe just look at the changing parts\n # TODO make it work for more boxes and goals\n # TODO test performace difference between deepcopy and copy\n\n # TODO TODO TODO only recalculate new parts of the shorest path. e.g.\n # calculate the distance from pos to Kp, and then simply calculate the distance from\n # Kp to Kp and add them together\n # maybe precalculate every keypoint?\n\n GTemp = copy.deepcopy(self.graph)\n # println(self.poses, self.poses[combId][pathId])\n startPos, endPos = self.poses[combId][pathId]\n currentPath = state.currentPath[combId][pathId]\n prevKeypoints = state.prevKeypoints[combId][pathId]\n # println(\" start\", startPos,endPos, state.currentPath, startId, endId)\n if (\n currentPath is not None\n ): # and #TODO find if inbetween two points! #G.has_node(state.currentPath[0]):\n # TODO don't re calculate the path\n # TODO do the same at the endPoint\n startKps, endKps = prevKeypoints\n # println(endKps, startKps)\n # println(state.currentPath)\n # println(startKp, boxKp, goalKp)\n # println(state.currentPath.index(startKp), boxKp, goalKp)\n\n if len(currentPath) > 2 and currentPath[1] == startPos:\n startKps = [currentPath[1], currentPath[2]]\n if len(currentPath) == 2:\n # println(endPos, startKps)\n startKps.append(endPos)\n\n # dist = manha_dist(startPos, state.currentPath[0])\n # GTemp.add_edge(startPos, state.currentPath[0], weight=dist)\n # dist = manha_dist(startPos, state.currentPath[1])\n # GTemp.add_edge(startPos, state.currentPath[1], weight=dist)\n\n for kp in startKps:\n dist = manha_dist(startPos, kp)\n GTemp.add_edge(startPos, kp, weight=dist)\n # GTemp.add_edge(startKp, startPos, weight=dist)\n # println(startKp, startPos)\n\n for kp in endKps:\n dist = manha_dist(endPos, kp)\n GTemp.add_edge(kp, endPos, weight=dist)\n\n # TODO do some magic for endPos\n # println(\"is neighbor\", startPos, startKp, endPos, boxKp, goalPos, goalKp)\n println(\"if\", startPos, startKps, endPos, endKps)\n self.draw(GTemp)\n length, newPath = nx.bidirectional_dijkstra(GTemp, startPos, endPos)\n\n # println(lengthBox, pathBox[1::], lengthGoal, pathGoal[2::])\n # println(startKp, startPos, boxKp, endPos, goalKp, goalPos)\n prevKeypoints = [startKps, endKps]\n\n # println(lengthBox,lengthGoal, pathBox, pathGoal)\n else:\n\n # println(startPos, endPos)\n startKps = self.findBestKeyPoint(startPos, endPos)\n endKps = self.findBestKeyPoint(endPos, startPos)\n # println(startKps, endKps)\n prevKeypoints = [startKps, endKps]\n # println(state.prevKeypoints, endKps)\n\n for kp in startKps:\n dist = manha_dist(startPos, kp)\n GTemp.add_edge(startPos, kp, weight=dist)\n\n for kp in endKps:\n dist = manha_dist(kp, endPos)\n GTemp.add_edge(kp, endPos, weight=dist)\n # GTemp.add_edge(endPos, endKp, weight=dist)\n\n # println(\"else\", startPos, startKps, endPos, endKps)\n # self.draw(GTemp)\n if nx.has_path(GTemp, startPos, endPos):\n length, newPath = nx.bidirectional_dijkstra(GTemp, startPos, endPos)\n else:\n return None\n del GTemp\n currentPath = newPath\n return length # path[1:-1]\n\n def initializeGraphAttributes(self, state, subGoal, i):\n self.poses[i] = subGoal\n if state.currentPath[i] is None:\n state.currentPath[i] = [None] * len(subGoal)\n state.prevKeypoints[i] = [None] * len(subGoal)\n\n def initializeGraphSizes(self, state, size):\n self.poses = [None] * size\n state.currentPath = [None] * size\n state.prevKeypoints = [None] * size\n\n def __call__(self, states: List):\n \"\"\"Calculate heuristic for states in place.\"\"\"\n if type(states) is not list:\n states = [states]\n if len(states) == 0:\n return None\n\n length = None\n for state in states:\n # Subproblems just have one agent\n agt_pos, color = list(state.agents.values())[0][0]\n length_boxes = 0\n length_goals = 0\n for goal, vals in state.goals.items():\n for v in vals:\n goal_pos, goal_color = v\n\n if color != goal_color:\n continue\n\n box_poses = [\n p_c[0][0]\n for box, p_c in state.boxes.items()\n if box.lower() == goal.lower()\n ]\n if any(goal_pos == box_pos for box_pos in box_poses):\n continue\n\n # (State, partsToSolve)\n this_boxes = []\n this_goals = []\n\n self.initializeGraphSizes(state, len(box_poses))\n\n for i, box_pos in enumerate(box_poses):\n if (goal, box_pos, agt_pos) in self.boxes:\n this_goal = self.boxes[(goal, box_pos, agt_pos)]\n h_box = this_goal[0]\n h_goal = this_goal[1]\n else:\n self.initializeGraphAttributes(\n state, [[agt_pos, box_pos], [box_pos, goal_pos]], i\n )\n h_box = self.findPathPart(state, 0, i)\n h_goal = self.findPathPart(state, 1, i)\n if h_box and h_goal:\n self.boxes[(goal, box_pos, agt_pos)] = h_box, h_goal\n\n # (State, partIndex)\n if h_box and h_goal:\n this_boxes.append(h_box)\n this_goals.append(h_goal)\n if this_boxes and this_goals:\n length_boxes += min(this_boxes)\n length_goals += sum(this_goals)\n\n length = length_boxes + length_goals * 2\n state.h = length\n state.f = state.h * 2 + state.g\n # println(state, state.h, state.g, state.f)\n","sub_path":"multi_sokoban/heuristics.py","file_name":"heuristics.py","file_ext":"py","file_size_in_byte":22563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"434160608","text":"import re\n# Работа со списками\n# Написать код для функций ниже\n# Проверка производится в функции main()\n\n# 00. Пример. Дан список (list) строк. Вернуть число - количество строк, у которых\n# 1. длина строки 2 и больше\n# 2. первый и последний символ одинаковые\n\ndef func00(words):\n count = 0\n for w in words:\n if len(w)>=2 and w[0]==w[-1]:\n count += 1\n return count\n\n\n# 01. Из списка строк вернуть список в отсортированном по алфавиту порядке, но строки \n# начинающиеся с числа (0-9) должны идти после строк, начинающихся с букв\n# Подсказка: можно создать два списка, отсортировать их по отдельности перед объединением\n\ndef func01(words):\n # здесь код и не забыть вернуть хоть что-то\n number_list = []\n word_list = []\n for word in words:\n if re.match(r'(\\d+\\w*)', word) is not None:\n number_list.append(word)\n else:\n word_list.append(word)\n return sorted(word_list) + sorted(number_list)\n\n\n# 02. Отсортировать по последнему\n# Дан список не пустых tuples, вернуть список, отсортированный по возрастанию\n# последнего элемента tuple\ndef func02(tuples):\n # здесь код и не забыть вернуть хоть что-то\n return sorted(tuples, key = lambda tup: tup[1])\n\n\n# используется для проверки, \ndef test(got, expected):\n if got == expected:\n prefix = ' OK '\n else:\n prefix = ' X '\n print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))\n\n\n# Запускает проверку\ndef main():\n print('func00')\n test(func00(['abba', 'xyz01', 'nn', 'y', '444']), 3)\n test(func00(['', 'a', 'ab', 'cvc', 'jj']), 2)\n test(func00(['rrr', 'db', 'pro', 'hello']), 1)\n\n print('func01')\n test(func01(['1aa', '2bb', 'axx', 'xzz', 'xaa']),\n ['axx', 'xaa', 'xzz', '1aa', '2bb'])\n test(func01(['ccc', 'bbb', '9aa', 'xcc', 'xaa']),\n ['bbb', 'ccc', 'xaa', 'xcc', '9aa'])\n test(func01(['mix', 'xyz', '6apple', 'xanadu', 'aardvark']),\n ['aardvark', 'mix', 'xanadu', 'xyz', '6apple'])\n\n print('func02')\n test(func02([(1, 3), (3, 2), (2, 1)]),\n [(2, 1), (3, 2), (1, 3)])\n test(func02([(2, 3), (1, 2), (3, 1)]),\n [(3, 1), (1, 2), (2, 3)])\n test(func02([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),\n [(2, 2), (1, 3), (3, 4, 5), (1, 7)])\n\nif __name__ == '__main__':\n main()\n","sub_path":"2018/01/01_Moldobaev.py","file_name":"01_Moldobaev.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"602030537","text":"visited = list()\n\n\ndef check_around(x, y, rows, columns, land):\n global visited\n my_size = 1\n\n # Upper left corner\n if x > 0 and y > 0 and not visited[x-1][y-1] and land[x-1][y-1] == 1:\n visited[x-1][y-1] = True\n my_size += check_around(x - 1, y - 1, rows, columns, land)\n\n # Upper same column\n if x > 0 and not visited[x-1][y] and land[x-1][y] == 1:\n visited[x - 1][y] = True\n my_size += check_around(x - 1, y, rows, columns, land)\n\n # Upper right corner\n if x > 0 and y < (columns-1) and not visited[x-1][y+1] and land[x-1][\n y+1] == 1:\n visited[x - 1][y + 1] = True\n my_size += check_around(x - 1, y + 1, rows, columns, land)\n\n # Same level left column\n if y > 0 and not visited[x][y-1] and land[x][y-1] == 1:\n visited[x][y - 1] = True\n my_size += check_around(x, y - 1, rows, columns, land)\n\n # Same level right column\n if y < (columns-1) and not visited[x][y+1] and land[x][y+1] == 1:\n visited[x][y + 1] = True\n my_size += check_around(x, y + 1, rows, columns, land)\n\n # Down left column\n if x < (rows-1) and y > 0 and not visited[x+1][y-1] and land[x+1][y-1] \\\n == 1:\n visited[x + 1][y - 1] = True\n my_size += check_around(x + 1, y - 1, rows, columns, land)\n\n # Down same column\n if x < (rows-1) and not visited[x+1][y] and land[x+1][y] == 1:\n visited[x + 1][y] = True\n my_size += check_around(x + 1, y, rows, columns, land)\n\n # Down right column\n if x < (rows-1) and y < (columns-1) and not visited[x+1][y+1] and land[\n x+1][y+1] == 1:\n visited[x + 1][y + 1] = True\n my_size += check_around(x + 1, y + 1, rows, columns, land)\n return my_size\n\n\ndef count_continents(land):\n global visited\n rows = len(land)\n if rows == 0:\n return 0\n columns = len(land[0])\n visited = [[False for j in range(0, columns)] for i in range(0, rows)]\n continent_sizes = list()\n for i in range(0, rows):\n for j in range(0, columns):\n if not visited[i][j] and land[i][j] == 1:\n visited[i][j] = True\n size = check_around(i, j, rows, columns, land)\n continent_sizes.append(size)\n return len(continent_sizes), continent_sizes\n\n\nif __name__ == '__main__':\n land = [\n [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0],\n [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]\n print(count_continents(land))\n","sub_path":"summer-of-code/week-01/wk1-hackathon-submissions/soc01h-cc-varsha-prabhu.py","file_name":"soc01h-cc-varsha-prabhu.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"559666053","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\"\"\"\nAuthor: Dylan Payton taken from FeedbackLCA code\nPad data with ones for visualization\nOutputs:\n padded version of input\nArgs:\n data: np.ndarray\n\"\"\"\n\ndef pad_data(data):\n n = int(np.ceil(np.sqrt(data.shape[0])))\n padding = (((0, n ** 2 - data.shape[0]),\n (1, 1), (1, 1)) # add some space between filters\n + ((0, 0),) * (data.ndim - 3)) # don't pad the last dimension (if there is one)\n padded_data = np.pad(data, padding, mode=\"constant\", constant_values=1)\n # tile the filters into an image\n padded_data = padded_data.reshape((n, n) + padded_data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, padded_data.ndim + 1)))\n padded_data = padded_data.reshape((n * padded_data.shape[1], n * padded_data.shape[3]) + padded_data.shape[4:])\n return padded_data\n\n\ndef normalize_data(data):\n norm_data = data.squeeze()\n if np.max(np.abs(data)) > 0:\n norm_data = (data / np.max(np.abs(data))).squeeze()\n return norm_data\n\n\n\"\"\"\nAuthor: Dylan Payton taken from FeedbackLCA code\nDisplay input data as an image with reshaping\nOutputs:\n fig: index for figure call\n sub_axis: index for subplot call\n axis_image: index for imshow call\nInpus:\n data: np.ndarray of shape (height, width) or (n, height, width)\n normalize: [bool] indicating whether the data should be streched (normalized)\n This is recommended for dictionary plotting.\n title: string for title of figure\n\"\"\"\ndef display_data_tiled(data, normalize=False, title=\"\", prev_fig=None):\n \n #calculate mean of each picture of weights\n mean_list =[]\n for x in data:\n mean_list.append(np.linalg.norm(np.reshape(x,-1),ord=2))\n #mean_list.append(np.linalg.norm(np.reshape(x,-1)))\n \n #Rescale data \n mean_data = np.mean(data)\n min_data = np.amin(data)\n max_data = np.amax(data)\n data = (((data-min_data)/(max_data-min_data))*2)-1\n \n if normalize:\n data = normalize_data(data)\n if len(data.shape) >= 3:\n data = pad_data(data)\n \n fig = plt.figure(figsize=(10,10))\n \n sub_axis = fig.add_subplot(2,1,1) \n axis_image = sub_axis.imshow(data, \n cmap=\"Greys_r\",\n interpolation=\"none\")\n axis_image.set_clim(vmin=-1.0, vmax=1.0)\n # Turn off tick labels\n sub_axis.set_yticklabels([])\n sub_axis.set_xticklabels([])\n cbar = fig.colorbar(axis_image)\n sub_axis.tick_params(\n axis=\"both\",\n bottom=\"off\",\n top=\"off\",\n left=\"off\",\n right=\"off\") \n \n bar_chart = fig.add_subplot(2,1,2)\n bar_chart.bar(range(0, len(mean_list)), mean_list, edgecolor = 'black', color = 'black')\n\n #fig.subtitle(title, y=1.05)\n fig.canvas.draw()\n #plt.show()\n \n return (fig, sub_axis, axis_image)\n\n\n\"\"\"\nAuthor: Vasha DuTell\nPlot to visualize the tiling of the center RF of on and off cells separately.\nOutputs:\n Figure object with two tiling plots, one with on, and the other with off cells.\nArgs:\n data: np.ndarray or list of weights, each an individiaul neuron RF\n\"\"\"\ndef plotonoff(allws):\n\n #extract on center\n onws = np.mean(allws,axis=0)>0\n onws = allws[:,onws]\n #extract off center\n offws = np.mean(allws,axis=0)<0\n offws = allws[:,offws]\n #keep track of the circles\n oncircs = []\n offcircs = []\n\n for ws in allws:\n circ = (ws>(0.9*np.sign(np.mean(ws))))\n if(np.mean(ws)>0):\n oncircs.append(circ)\n else:\n offcircs.append(False==circ)\n\n #plot\n fig = plt.figure(figsize=(6,3.5))\n plt.subplot(1,2,1,title='On') \n oncolors = iter(plt.cm.jet(np.linspace(0,1,len(oncircs)))) \n for onc in oncircs: \n plt.contour(onc,[0.7],linewidths = 3,colors=[next(oncolors)])\n plt.xticks([])\n plt.yticks([])\n \n plt.subplot(1,2,2,title='Off')\n offcolors = iter(plt.cm.jet(np.linspace(0,1,len(offcircs)))) \n for ofc in offcircs:\n plt.contour(ofc,[0.7], linewidths = 3, colors=[next(offcolors)])\n plt.xticks([])\n plt.yticks([])\n plt.tight_layout()\n \n return(fig)\n\n\n\n\ndef save_plots(aec,\n activations,\n cost_evolution,\n wmean_evolution,\n inweights_evolution,\n outweights_evolution,\n images,\n recons,\n final_inweights,\n final_outweights,\n inbias_evolution,\n activation_evolution,\n gamma_evolution,\n gamma_assign_evolution):\n \n savefolder = aec.params['savefolder']\n\n #Save our final weights\n inweights_evolution_r = np.rollaxis(np.reshape(inweights_evolution,\n (len(inweights_evolution),\n aec.params['imxlen'],\n aec.params['imylen'],\n aec.params['nneurons'])),3,1)\n (f,sa,ai) = display_data_tiled(inweights_evolution_r[-1], normalize=True, title=\"final_in_weights\", prev_fig=None);\n f.savefig(savefolder+'inweights_final.png')\n plt.close() \n \n outweights_evolution_r = np.reshape(outweights_evolution,\n (len(outweights_evolution),\n aec.params['nneurons'],\n aec.params['imxlen'],\n aec.params['imylen'])) #no rollaxis needed b/c shape is already nnuerons in pos 1.\n \n (f,sa,ai) = display_data_tiled(outweights_evolution_r[-1], normalize=True, title=\"final_out_weights\", prev_fig=None);\n f.savefig(savefolder+'outweights_final.png')\n plt.close()\n\n #save evolving weights\n for i in range(len(inweights_evolution_r)):\n (f,sa,ai) = display_data_tiled(inweights_evolution_r[i], normalize=True,title=\"inweights_evolving\", prev_fig=None);\n f.savefig(savefolder+'/inweights_evolution_'+str(i)+'.png')\n plt.close()\n \n (f,sa,ai) = display_data_tiled(outweights_evolution_r[i], normalize=True,title=\"outweights_evolving\", prev_fig=None);\n f.savefig(savefolder+'/outweights_evolution_'+str(i)+'.png')\n plt.close()\n \n #save plot of activations\n f8 = plt.figure(figsize=(6,6))\n plt.plot(activations)\n plt.title('Activations')\n f8.savefig(savefolder+'/activations.png') \n plt.close()\n \n #save weights and cost evolution\n f2 = plt.figure(figsize=(6,6))\n plt.subplot(2,1,1,title='Weights_Mean')\n plt.plot(wmean_evolution)\n plt.subplot(2,1,2,title='Cost')\n plt.plot(cost_evolution)\n #plt.plot(cost_evolution/2)\n plt.tight_layout()\n f2.savefig(savefolder+'/cost_weights.png') \n plt.close()\n \n #show an example image and reconstruction from the last iteration of learning\n patchnum = 3\n plots = 4\n f3 = plt.figure()\n for i in range(plots):\n plt.subplot(plots,2,2*i+1)#,title='Patch')\n plt.imshow(images[-1][patchnum+i],cmap='gray',interpolation='none')\n plt.colorbar()\n plt.axis('off')\n\n plt.subplot(plots,2,2*i+2)#,title='Recon')\n plt.imshow(recons[-1][patchnum+i],cmap='gray',interpolation='none')\n plt.colorbar()\n plt.axis('off')\n\n plt.tight_layout()\n f3.savefig(savefolder+'/reconstruction.png') \n plt.close() \n \n #save plots of on and off tiling\n f4 = plotonoff(inweights_evolution_r[-1]);\n f4.savefig(savefolder+'/final_in_on_off_RFs.png') \n plt.close()\n \n #save plots of on and off tiling\n f5 = plotonoff(outweights_evolution_r[-1]);\n f5.savefig(savefolder+'/final_out_on_off_RFs.png') \n plt.close()\n \n \n #save plots of activation and gamma\n for i in range(len(activation_evolution)):\n f6 = plt.figure()\n plt.bar(range(0, len(activation_evolution[i])), activation_evolution[i], edgecolor = 'black', color = 'black')\n f6.savefig(savefolder+'/activation_'+str(i)+'.png')\n plt.close()\n for i in range(len(gamma_evolution)):\n f7 = plt.figure()\n plt.bar(range(0, len(gamma_evolution[i])), gamma_evolution[i], edgecolor = 'black', color = 'black')\n f7.savefig(savefolder+'/gamma_'+str(i)+'.png')\n plt.close()\n for i in range(len(gamma_assign_evolution)):\n f8 = plt.figure()\n plt.bar(range(0, len(gamma_assign_evolution[i])), gamma_assign_evolution[i], edgecolor = 'black', color = 'black')\n f8.savefig(savefolder+'/gamma_assign'+str(i)+'.png')\n plt.close()\n for i in range(len(inbias_evolution)):\n f9 = plt.figure()\n plt.bar(range(0, len(inbias_evolution[i])), inbias_evolution[i], edgecolor = 'black', color = 'black')\n f9.savefig(savefolder+'/inbias_'+str(i)+'.png')\n plt.close()\n \n ","sub_path":"utils/plotutils.py","file_name":"plotutils.py","file_ext":"py","file_size_in_byte":8947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"399274903","text":"import tweepy\nimport sys\nimport sqlite3\nfrom sqlite3 import Error\nimport time\n\n\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, wait_on_rate_limit=True)\n\n\n# http://www.sqlitetutorial.net/sqlite-python/insert/\n\ndef create_connection(db_file):\n \"\"\"Create a database connection to the SQLite database\n param db_file: database file for database\n return: connection object or None\"\"\"\n\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n\ndef write_articles_by_screen_name(conn, t_screen_name):\n try:\n t_sql = '''INSERT INTO main_articles(article_id, author, title , source_url) VALUES(?, ?, ? ,?)'''\n\n cur = conn.cursor()\n cur.execute(t_sql, t_screen_name)\n except Error as e:\n print(e)\n return cur.lastrowid\n\ndef link_comments_to_articles(conn):\n cursor = conn.execute(\"UPDATE main_comments SET article_id=(SELECT article_id FROM main_articles WHERE author = main_comments.screen_name);\")\n conn.commit()\n\n\ndef build_articles_by_screen_name(conn):\n cursor = conn.execute(\"select distinct user_screen_name, user_name from main_tweets\")\n i = 1\n for row in cursor:\n user_url = 'https://twitter.com/'+row[0]\n article_payload = (i, row[0], row[0], user_url)\n recId = write_articles_by_screen_name(conn, article_payload)\n i +=1\n conn.commit()\n return True\n\n\ndef write_comments_by_screen_name(conn, t_tweet):\n #print(t_tweet)\n t_sql = '''INSERT INTO main_comments(screen_name, comment_raw) VALUES(?, ?)'''\n try:\n cur = conn.cursor()\n cur.execute(t_sql, t_tweet)\n except Error as e:\n print(e)\n return cur.lastrowid\n\n\ndef build_comments_by_screen_name(conn):\n cursor = conn.execute(\"select distinct id_str, tweet_id, tweet_text, user_screen_name, topic \"\n \"from main_tweets order by user_screen_name\")\n master_comments = {}\n current_screen_name = 'NULL'\n work_string = ''\n i = 0\n for row in cursor:\n i += 1\n if current_screen_name == row[3]:\n work_string = work_string + ' |||||t' + row[2].replace('\\n', '').replace('\\r', '')\n else:\n master_comments[current_screen_name] = work_string\n work_string = ''\n work_string = row[2].replace('\\n', '').replace('\\r', '') + '\\t'\n current_screen_name = row[3]\n return master_comments\n\ndef clean_comments(conn):\n cursor = conn.execute(\"update main_comments set comment_clean = replace(replace(comment_raw,'#',''),'@','')\")\n conn.commit()\n\ndef db_create_tweet(conn, t_tweet):\n print(t_tweet)\n t_sql = '''INSERT INTO main_tweets(id_str, tweet_text, user_screen_name, created_at, topic) VALUES(?, ?, ? ,?, ?)'''\n cur = conn.cursor()\n cur.execute(t_sql, t_tweet)\n return cur.lastrowid\n\ndef hashtag_list():\n hashtags = {'#democrat': 100, \"#danger\": 100, '#republican': 100, '#breaking': 100, '#china': 100, '#russia': 100,\n '#healthinsurance': 100, '#fraud': 100, '#surveillance': 100, '#measles': 100, '#felony': 100,\n '#drug': 100, '#mueller': 100, '#arrest': 100, '#criminal': 100, '#police': 100,\n '@CNN': 100, '#Foxnews': 100, '#shooting': 1000, '@realdonaldtrump': 1500, '#terrorism': 1500,\n '#fishing': 1500, '#python': 1500, '#UIUC': 1500, \"#buildawall\": 1000, \"@OCSheriff\": 750,\n \"#illegal\": 100, '#hate': 1000, '@elonmusk': 100, '#mexico': 100, '#buildthewall': 100,\n '#teens': 100, '#coursera': 100, '@speakerpelosi': 100, '#victim': 100, '#FBI': 100,\n '#disneyland': 100, '#stocks': 100, '#CIA': 100, '#FBI': 100, '#CBP': 100,\n '#MAGA': 100, '#OCREgister': 100, '#school': 100, '#california': 100, '#mexico': 100,\n '#healthcare': 100, '#april': 100, '#endgame': 100, '#student': 100, '#theif': 100,\n '#SB54': 100, \"#losangeles\": 100, \"#world\": 100, \"#UN\": 100, \"#newyork\": 100,\n '#hacker': 100, '#may': 100, '#zombie': 100, '#today': 100, '#GOT': 100,\n '@wapo': 100, \"#nytimes\": 100, '#HBPD': 100, \"#google\": 100, \"#rally\": 100,\n '#opioids': 100, '#HIV': 100, '#religion': 100, '#trending': 100, '@WSJ': 100, '@cnnpolitics': 100,\n '#fakenews': 100, '#media': 100}\n clear_hashtags_from_db(conn)\n for hashtag, last_id in hashtags.items():\n hashtag_string = (hashtag, last_id)\n write_hashtag_to_db(conn, hashtag_string)\n\n return hashtags\n\ndef clear_hashtags_from_db(conn):\n print('Deleting existing hashtags and resetting')\n cur = conn.execute('Delete from main_hashtags')\n\ndef write_hashtag_to_db(conn, topic):\n cur = conn.execute\n print('writing hashtag to database', topic)\n t_sql = '''INSERT INTO main_hashtags(hashtag_string, hashtag_lastvalue) VALUES(?, ?)'''\n try:\n cur = conn.cursor()\n cur.execute(t_sql, topic)\n except Error as e:\n print(e)\n print('success')\n conn.commit()\n return cur.lastrowid\n\n\n\n\ndef main(topics, conn):\n\n f_tweet = {}\n replies = []\n count = 1\n for topic, start in topics.items():\n print(topic)\n print(\"running for topic: \", topic, \" starting at tweet:\")\n with conn:\n non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)\n for full_tweets in tweepy.Cursor(api.search, q=topic + \" -filter:retweets\", count=500, lang=\"en\", since=\"2019-04-01\").items(500):\n art_payload = full_tweets.id_str+\";\"+full_tweets.user.screen_name+\";\" + \\\n full_tweets.text.translate(non_bmp_map).replace('\\n', ' ').replace('\\r', '').replace(';', ':')\n comment = \"\"\n ft_sql_pay_load = (full_tweets.id_str, full_tweets.text.translate(non_bmp_map),\n full_tweets.user.screen_name, full_tweets.created_at, topic);\n ft_id = db_create_tweet(conn, ft_sql_pay_load)\n count +=1\n\n f_tweet.update({full_tweets.id_str: art_payload})\n print(\"starting wait\")\n sleep_time = 10\n for i in range(6):\n print('sleeping for ',sleep_time,' seconds, step:', 6-i)\n time.sleep(sleep_time)\n\n #build_articles_by_screen_name(conn)\n #master_comments = build_comments_by_screen_name(conn)\n #for key, value in master_comments.items():\n # ft_sql_pay_load = (key, value);\n # ft_id = write_comments_by_screen_name(conn, ft_sql_pay_load)\n # print(ft_id)\n\n\n\n#setup the base database connection\ndb_name = '..\\db.sqlite3'\nconn = create_connection(db_name)\n#get our list of hashtags (TODO: move this to db later)\n\ntopics_new =hashtag_list()\n\n#run our main twitter extract, TODO: split this up into smaller functions\n#main(topics_new, conn)\n\nbuild_articles_by_screen_name(conn)\nmaster_comments = build_comments_by_screen_name(conn)\n\nfor key, value in master_comments.items():\n ft_sql_pay_load = (key, value);\n ft_id = write_comments_by_screen_name(conn, ft_sql_pay_load)\n\nlink_comments_to_articles(conn)\n\n#Because the comments come in with # and @, lets remove those so they do not interfer with rank function\nclean_comments(conn)\n#make sure everything gets pushed to the DB\nconn.commit()\nconn.close()\n\n","sub_path":"main/import_tweets.py","file_name":"import_tweets.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"123843004","text":"#!/usr/bin/python3\n\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport datetime\nimport copy\nimport traceback\nimport mts_util\nimport subprocess\n\nTradableKeys = [\"symbol\", \"exch_symbol\", \"venue\", \"tick_size\", \\\n \"point_value\", \"px_multiplier\", \"type\", \\\n \"mts_contract\", \"contract_month\", \"mts_symbol\", \\\n \"N\", \"expiration_days\", \"tt_security_id\", \\\n \"tt_venue\", \"currency\", \"expiration_date\",\"bbg_id\",\\\n \"bbg_px_multiplier\", \"tickdata_id\", \\\n \"tickdata_px_multiplier\", \"tickdata_timezone\", \\\n \"lotspermin\", \"start_time\", \"end_time\"]\n\nTradableKeysSpread = [\"S\"]\n\ndef gen_asset_root(xml_path, assets_xml) :\n xml_cfg = xml_path + \"/\" + assets_xml\n root = ET.parse(xml_cfg).getroot()\n return root\n\ndef get_symbol_spread_set(cfg = '/home/mts/run/config/main.cfg'):\n mts_cfg = mts_util.MTS_Config(cfg)\n spread_dict = {}\n try:\n keys = mts_cfg.listSubKeys('Spreads')\n for k in keys:\n kl = int(mts_cfg.arrayLen('Spreads.'+k))\n sa = []\n for i in np.arange(kl).astype(int):\n sa.append(tuple(mts_cfg.getArr('Spreads.%s[%d]'%(k,i), int)))\n spread_dict[k] = copy.deepcopy(sa)\n except:\n #traceback.print_exc()\n print('no symbol spread definitions found')\n return spread_dict\n\ndef get_max_N(cfg = '/home/mts/run/config/main.cfg'):\n mts_cfg = mts_util.MTS_Config(cfg)\n return mts_cfg.get('MaxN',int)\n\ndef update_symbol_map(today_yyyy_mm_dd, xml_path, max_N = 2, assets_xml = \"assets.xml\", mts_symbols=None, root = None, symbol_spread_dict={}, add_prev_day_symbols=False):\n \"\"\"\n Input: \n today_yyyy_mm_dd: today's date as yyyy-mm-dd\n xml_path: the path to the mappings xml, i.e. config/symbol\n max_N: number of contracts to include for each future symbol\n assets_xml: the xml file, ie. assets.xml\n mts_symbols: optional list of mts_symbols (taken without _N, otherwise ignores _N) \n to generate mappings for. If None then generates all.\n root: optional xml root if None then generates from xml_path\n spread_list: optional dictionary of per-symbol list of N1-N2 pairs to be added.\n i.e. {'WTI':[(1,6), (1,12)]}, to add spreads N1-N6 and N1-N12 (in addition to defaults)\n Note, if not specified, it adds [(0,1),(0,2),(1,2)] by default\n add_prev_day_symbols: in case today's holiday (and half day) for some symbols, they won't be \n in today's symbol_map and therefore the bpmain/tpmain won't \n subscribe them. This could lead to issues such as next day's open referring\n to the previous day's close, making the overnight return bigger than reality.\n Set this true to include previous day's symbols if they are not in today's map.\n Symbols are 'WTI','Brent', etc.\n\n return :\n it reads assets.xml and roll_schedules/* \n and parse into a list of tradable and a dict of venues for current day:\n tradable = [ \n {\n tradable = ESH1\n symbol = SPX\n exch_symbol = ES\n venue = CME\n currency = USD\n tick_size = 0.25\n point_value = 50\n px_multiplier = 0.01\n type = FUT\n\n mts_contract = SPX_202103\n contract_month = 202103\n mts_symbol = SPX_N1\n N = 1\n expiration_days = 4\n tt_security_id = 0123455\n tt_venue = CME\n subscribed = 0\n bbg_id = ESH1 INDEX\n bbg_px_multiplier = 1.0\n tickdata_id = ESH21\n tickdata_px_multiplier = 0.01\n lotspermin = 40\n\n start_time = 20210214-18:00:00\n end_time = 20210214-17:00:00\n }\n ...\n ]\n\n venue = {\n CME = {\n hours = [ -6, 0, 17, 0 ]\n }\n }\n \"\"\"\n\n if mts_symbols is not None:\n # remove \"_N?\" from mts_symbols if exists\n symbols0 = set()\n for symbol in mts_symbols :\n symbols0.add(symbol.split('_')[0])\n mts_symbols = symbols0\n\n today = today_yyyy_mm_dd\n if '-' not in today_yyyy_mm_dd and len(today_yyyy_mm_dd) == 8 :\n today = today_yyyy_mm_dd[:4] + '-' + today_yyyy_mm_dd[4:6] + '-' + today_yyyy_mm_dd[6:]\n #today += \" 00:00:00\"\n\n if root is None :\n root = gen_asset_root(xml_path, assets_xml)\n\n tradable = []\n venues = {}\n\n max_Nsp = max_N\n default_spread_list = [(0,1),(0,2),(1,2)]\n\n for assets in root :\n sym = {}\n max_Nsp = max_N\n spread_set = set(default_spread_list)\n for asset in assets :\n if asset.tag == \"symbol\" :\n if mts_symbols is not None and len(mts_symbols)>0 and asset.text not in mts_symbols :\n break\n sym[\"symbol\"] = asset.text\n if asset.text in symbol_spread_dict.keys():\n spread_set=set(default_spread_list+symbol_spread_dict[asset.text])\n for (n1,n2) in spread_set:\n max_Nsp=max(max_Nsp,n2)\n elif asset.tag == \"exchange_symbol\":\n sym[\"exch_symbol\"] = asset.text\n elif asset.tag == \"currency\" :\n sym[\"currency\"] = asset.text\n elif asset.tag == \"exchange\" :\n sym[\"venue\"] = asset.text\n elif asset.tag == \"ticksize\" :\n sym[\"tick_size\"] = asset.text\n elif asset.tag == \"spread_ticksize\" :\n sym[\"spread_tick_size\"] = asset.text\n elif asset.tag == \"currency\" :\n sym[\"currency\"] = asset.text\n elif asset.tag == \"calendar\" :\n cal_file = xml_path + \"/calendars/\" + asset.text\n\n sym[\"cal\"] = {\"file\": cal_file}\n # getting the calendar for first max_N contract of today,\n # include N0, N1, etc\n c = np.genfromtxt(cal_file, delimiter = \",\", dtype = \"|S32\")\n try :\n ct = c[np.nonzero(c[:,0] == str.encode(today))[0][0]]\n s = ct[2].decode()\n e = ct[3].decode()\n if s == \"\" or e == \"\" :\n # not a trading day\n raise RuntimeError(today + \" is not a trading day from calendar\")\n sym[\"cal\"][\"s\"] = s\n sym[\"cal\"][\"e\"] = e\n sym[\"expiration_days\"] = int(ct[6])\n # read upto max_N contracts into \"contracts\"\n # for N = 0, 1, .., max_Nsp\n sym[\"contracts\"] = []\n for n in np.arange(max_Nsp+1).astype(int) :\n sym[\"contracts\"].append(ct[7+n].decode())\n sym[\"start_time\"] = s.split(' ')[1]\n sym[\"end_time\"] = e.split(' ')[1]\n\n except :\n #traceback.print_exc()\n #raise TradingDayError( today + \" is not a trading day from \" + cal_file)\n #print ( today + \" is not a trading day from \" + cal_file)\n break\n\n # set the venue\n if \"venue\" in sym.keys() :\n v = sym[\"venue\"]\n if v in venues.keys() :\n if venues[v][\"s\"] != s or venues[v][\"e\"] != e :\n #print (\"venue hour update for \" + v)\n if venues[v][\"s\"] > s :\n venues[v][\"s\"] = s\n if venues[v][\"e\"] < e :\n venues[v][\"e\"] = e\n else :\n venues[v] = {\"s\": s, \"e\": e}\n\n elif asset.tag == \"providers\" :\n # getting the tt's px mul\n # and tickdata's px_multiplier and timezone\n for p in asset :\n if p.tag == \"tt\" :\n for p0 in p :\n if p0.tag == \"px_multiplier\" :\n sym[\"px_multiplier\"] = p0.text\n if p0.tag == \"exchange\":\n sym[\"tt_venue\"] = p0.text\n elif p.tag == \"tickdata\" :\n for p0 in p :\n if p0.tag == \"px_multiplier\" :\n sym[\"tickdata_px_multiplier\"] = p0.text\n elif p0.tag == \"timezone\" :\n sym[\"tickdata_timezone\"] = p0.text\n elif p.tag == \"bbg\" :\n for p0 in p :\n if p0.tag == \"px_multiplier\" :\n sym[\"bbg_px_multiplier\"] = p0.text\n\n elif asset.tag == \"execution\" :\n # getting the twap lotspermin\n for p in asset :\n if p.tag == \"twap\" :\n for p0 in p :\n if p0.tag == \"lotspermin\":\n sym[\"lotspermin\"] = p0.text\n\n elif asset.tag == \"contracts\" :\n # getting the tradable name\n for c in asset :\n con0 = {'type':'FUT'}\n for f in c :\n if f.tag == \"pointvalue\" :\n con0[\"point_value\"] = f.text\n elif f.tag == \"expiry\" :\n expiry = f.text\n if expiry not in sym[\"contracts\"] :\n con0 = {}\n break\n n = np.nonzero(np.array(sym[\"contracts\"])==expiry)[0][0]\n con0[\"contract_month\"] = expiry\n con0[\"N\"] = n\n elif f.tag == \"tt_exchange_id\" :\n con0[\"tradable\"] = f.text\n elif f.tag == \"tt_security_id\" :\n con0[\"tt_security_id\"] = f.text\n elif f.tag == \"expiration_date\" :\n con0[\"expiration_date\"] = f.text\n elif f.tag == \"bbg_id\" :\n con0[\"bbg_id\"] = f.text\n elif f.tag == \"tickdata_id\" :\n con0[\"tickdata_id\"] = f.text\n elif f.tag == \"symbol\" :\n con0[\"mts_contract\"] = f.text\n\n if len(con0.keys()) >= 4 :\n sym[n] = copy.deepcopy(con0)\n\n elif asset.tag == \"spreads\":\n # getting the tradable name\n for c in asset :\n con0 = {'type':'MLEG'}\n for f in c :\n if f.tag == \"pointvalue\" :\n con0[\"point_value\"] = f.text\n elif f.tag == \"expiry\" :\n expiry1,expiry2 = f.text.split('-')\n if expiry1 not in sym[\"contracts\"] or expiry2 not in sym[\"contracts\"]:\n con0 = {}\n break\n n1 = np.nonzero(np.array(sym[\"contracts\"])==expiry1)[0][0]\n n2 = np.nonzero(np.array(sym[\"contracts\"])==expiry2)[0][0]\n if (n1,n2) not in spread_set:\n break\n con0[\"contract_month\"] = \"%s-%s\"%(expiry1,expiry2)\n con0[\"N\"] = n1\n con0[\"S\"] = n2\n\n elif f.tag == \"tt_exchange_id\" :\n con0[\"tradable\"] = f.text\n elif f.tag == \"tt_security_id\" :\n con0[\"tt_security_id\"] = f.text\n elif f.tag == \"bbg_id\" :\n con0[\"bbg_id\"] = f.text\n elif f.tag == \"tickdata_id\" :\n con0[\"tickdata_id\"] = f.text\n elif f.tag == \"symbol\" :\n con0[\"mts_contract\"] = f.text\n\n if len(con0.keys()) >= 4 and 'S' in con0.keys():\n if n1 not in sym.keys():\n raise RuntimeError(\"spread contract defined before underlying\")\n if 'spreads' not in sym[n1].keys():\n sym[n1]['spreads'] = []\n sym[n1]['spreads'].append(copy.deepcopy(con0))\n\n # finish parsing this asset into sym\n # write maxN tradable into trd \n # \n for n in np.arange(max_Nsp+1).astype(int) :\n if n not in sym.keys() :\n continue\n\n sym0 = copy.deepcopy(sym)\n sym0.update(sym[n])\n\n # for underlying types (FUT)\n if n <= max_N :\n sym0[\"mts_symbol\"] = sym[\"symbol\"] + \"_N\"+str(n)\n trd0 = {}\n for k in TradableKeys :\n # write to the files\n try :\n trd0[k] = sym0[k]\n except :\n if 'tickdata' not in k:\n print (k + \" is not defined \" + str(sym0[\"symbol\"]))\n trd0[k] = 'None'\n\n trd0[\"tradable\"] = sym0[\"tradable\"]\n if trd0['expiration_date'] <= today :\n # only add contracts expires later than today\n continue\n tradable.append(copy.deepcopy(trd0))\n\n # for the spread with n1=n\n if 'spreads' not in sym0.keys():\n continue\n for spd_con in sym0['spreads']:\n # we don't need this check, all spd_con should be in the set\n #if (n, spd_con['S']) not in spread_set:\n # continue\n trd0 = {}\n sym1=copy.deepcopy(sym0)\n sym1.update(spd_con)\n for k in TradableKeys + TradableKeysSpread:\n # write to the files\n try :\n trd0[k] = sym1[k]\n except :\n if 'tickdata' not in k :\n print (k + \" is not defined \" + str(sym0[\"symbol\"]))\n trd0[k] = 'None'\n\n trd0[\"mts_symbol\"] = sym1[\"symbol\"] + \"_N\"+str(n)+'-'+sym1['symbol']+'_N'+str(spd_con['S'])\n trd0[\"tradable\"] = sym1[\"tradable\"]\n trd0['tick_size'] = sym1['spread_tick_size']\n tradable.append(copy.deepcopy(trd0))\n\n\n if add_prev_day_symbols:\n # called from launch to add previous day's symbol in the symbol map for subscription/reference purpose for MTS engine\n tdi = mts_util.TradingDayIterator(today_yyyy_mm_dd)\n tdi.begin()\n prev_day=tdi.prev()\n tp, vp = update_symbol_map(prev_day, xml_path, max_N = max_N, assets_xml = assets_xml, mts_symbols=mts_symbols, root = root, symbol_spread_dict=symbol_spread_dict, add_prev_day_symbols=False)\n # merge symbols that are in tp into tradable\n cur_symbols = []\n for td in tradable:\n cur_symbols.append(td['symbol'])\n for td in tp:\n if td['symbol'] not in cur_symbols:\n tradable.append(td)\n # merge venue\n for vk in vp.keys():\n if vk not in venues.keys():\n venues[vk] = vp[vk]\n\n return tradable, venues\n\n\ndef writeToConfigure(tradable, venues, cfg_path, map_file = \"symbol_map.cfg\") :\n \"\"\"\n persist the two dictionaries to cfg_path/map_file\n \"\"\"\n\n with open(cfg_path + \"/\" + map_file, \"w\") as f :\n f.write(\"tradable = {\\n\")\n for trd in tradable :\n f.write(\" \" + trd[\"tradable\"] + \" = {\\n\")\n for key in TradableKeys+TradableKeysSpread:\n if key in trd.keys():\n f.write(\" \" + key + \" = \" + str(trd[key])+ \"\\n\")\n f.write(\" \" + \"}\\n\")\n\n f.write(\"}\\n\")\n f.write(\"venue = {\\n\")\n for key in venues.keys() :\n f.write(\" \" + key + \" = {\\n\")\n s = venues[key][\"s\"]\n e = venues[key][\"e\"]\n\n sh = int(s.strip().split(\" \")[1].split(\":\")[0])\n sm = int(s.strip().split(\" \")[1].split(\":\")[1])\n eh = int(e.strip().split(\" \")[1].split(\":\")[0])\n em = int(e.strip().split(\" \")[1].split(\":\")[1])\n\n if sh > eh or (sh == eh and sm >= em) :\n sh = sh - 24\n\n f.write(\" hours = [ \" + str(sh) + \", \" + str(sm) + \", \" + str(eh) + \", \" + str(em) + \" ]\\n\")\n f.write(\" }\\n\")\n f.write(\"}\\n\")\n\nclass SymbolMap :\n def __init__(self, xml_path = '/home/mts/run/config/symbol', max_N = 2, assets_xml = \"assets.xml\", default_symbol_spread_dict={}, main_cfg_fn = None):\n self.xml_path = xml_path\n assert max_N <= 6, \"max_N more than 6 - calendar file limit 6, run twice to get 12\"\n self.max_N = max_N\n self.assets_xml = assets_xml\n self.assets_root = None\n self.default_symbol_spread_dict = default_symbol_spread_dict \n if main_cfg_fn is not None:\n self.default_symbol_spread_dict = get_symbol_spread_set(main_cfg_fn)\n self.max_N = get_max_N(main_cfg_fn)\n\n def update_config(self, today_yyyy_mm_dd, cfg_path = 'config', map_file = 'symbol_map.cfg', mts_symbols = None, symbol_spread_dict={}):\n if len(symbol_spread_dict) == 0:\n symbol_spread_dict = self.default_symbol_spread_dict\n self._get_assets_root()\n t,v = update_symbol_map(today_yyyy_mm_dd, self.xml_path, self.max_N, self.assets_xml, mts_symbols = mts_symbols, root = self.assets_root, symbol_spread_dict=symbol_spread_dict)\n writeToConfigure(t, v, cfg_path, map_file)\n\n def get_tradable_map(self, today_yyyy_mm_dd, mts_key = False, mts_symbols = None, symbol_spread_dict={}, add_prev_day=False, optional_key_name=None) :\n \"\"\"\n if mts_key is True, map have key on mts_symbol, otherwise, key is tradable\n return :\n dict with key being either tradable or mts_symbol, value being the tradable dict\n \"\"\"\n if len(symbol_spread_dict) == 0:\n symbol_spread_dict = self.default_symbol_spread_dict\n self._get_assets_root()\n t,v = update_symbol_map(today_yyyy_mm_dd, self.xml_path, self.max_N, self.assets_xml, mts_symbols=mts_symbols, root=self.assets_root, symbol_spread_dict=symbol_spread_dict)\n smap = {} # a map from mts_symbol to a tradable\n key_name = 'mts_symbol'\n if not mts_key:\n if optional_key_name is not None:\n key_name = optional_key_name\n else:\n key_name = 'tradable'\n for t0 in t :\n #k = t0[\"mts_symbol\"] if mts_key else t0[\"tradable\"]\n k = t0[key_name]\n smap[k] = copy.deepcopy(t0)\n\n if add_prev_day:\n # add symbols that were tradable on previous day but not on today\n # to the smap\n tdi = mts_util.TradingDayIterator(today_yyyy_mm_dd)\n tdi.begin()\n prev_day = tdi.prev()\n smap_prev = self.get_tradable_map(prev_day, mts_key= mts_key, mts_symbols=mts_symbols, \\\n symbol_spread_dict=symbol_spread_dict, add_prev_day = False, optional_key_name=optional_key_name)\n for k in smap_prev.keys():\n if k not in smap.keys():\n smap[k] = smap_prev[k]\n return smap\n\n @staticmethod\n def is_mts_symbol(mts_or_tradable):\n \"\"\"look for pattern that either has '_N[012...9]' or '_yyyymm'\n \"\"\"\n tf = mts_or_tradable.split('_')\n if len(tf)>1:\n tf0 = tf[-1]\n if tf0[0]=='N':\n try:\n n_contract = int(tf0[1:])\n return True\n except:\n pass\n elif len(tf0)==6:\n try:\n contract_month = int(tf0)\n return True\n except:\n pass\n return False\n\n def get_tinfo(self, mts_or_tradable, yyyymmdd = None, is_mts_symbol = False, symbol_spread_dict={}, add_prev_day=False, optional_key_name=None) :\n if len(symbol_spread_dict) == 0:\n symbol_spread_dict = self.default_symbol_spread_dict\n if yyyymmdd is None :\n yyyymmdd = datetime.datetime.now().strftime('%Y%m%d')\n\n is_mts_symbol0 = SymbolMap.is_mts_symbol(mts_or_tradable)\n if is_mts_symbol is None:\n is_mts_symbol=is_mts_symbol0\n elif is_mts_symbol0 != is_mts_symbol:\n print('got %s, which %s a MTS symbol, but was given otherwise, please fix'%(mts_or_tradable, 'is' if is_mts_symbol0 else 'is NOT'))\n try :\n # try it as mts symbol, \n mts_symbols = [mts_or_tradable] if is_mts_symbol else None\n\n # this uses the mts_symbol as key, i.e. WTI_N1\n smap = self.get_tradable_map(yyyymmdd, mts_key = True, mts_symbols = mts_symbols, symbol_spread_dict=symbol_spread_dict, add_prev_day=add_prev_day, optional_key_name=optional_key_name)\n return smap[mts_or_tradable]\n except :\n try :\n if is_mts_symbol0 and optional_key_name is None:\n # this uses the mts_contract as key, i.e. WTI_202209\n smap = self.get_tradable_map(yyyymmdd, mts_key = False, mts_symbols = mts_symbols, symbol_spread_dict=symbol_spread_dict,add_prev_day=add_prev_day, optional_key_name='mts_contract')\n else:\n # this uses the 'exchange symbol as key, i.e. CLU2\n smap = self.get_tradable_map(yyyymmdd, mts_key = False, mts_symbols = mts_symbols, symbol_spread_dict=symbol_spread_dict,add_prev_day=add_prev_day, optional_key_name=optional_key_name)\n return smap[mts_or_tradable]\n except :\n raise KeyError(\"failed to get tinfo \" + mts_or_tradable)\n \n def list_symbol(self, today_yyyymmdd = None, mts_symbol_list=None, add_prev_day=False) :\n \"\"\"\n return a list of symbol, such as WTI, SPX, from mts_symbol, such as WTI_N1. \n if None then list all defined in assets.xml for today_yyyymmdd\n \"\"\"\n if today_yyyymmdd is None :\n today_yyyymmdd = datetime.datetime.now().strftime('%Y%m%d')\n tdi = mts_util.TradingDayIterator(today_yyyymmdd)\n today_yyyymmdd=tdi.begin()\n smap = self.get_tradable_map(today_yyyymmdd, mts_key = True, mts_symbols=mts_symbol_list, add_prev_day=add_prev_day)\n if mts_symbol_list is None:\n mts_symbol_list = smap.keys()\n\n symbols = []\n for k in mts_symbol_list:\n sym = smap[k]['symbol']\n if sym not in symbols: \n symbols.append(sym)\n return symbols\n\n def get_tradable_from_mts_symbol(self, mts_symbol_arr, trade_day) :\n \"\"\"\n get an array of tradables given mts_symbols and a trading day\n Note the returned array has same length with mts_symbol_arr. If not a trading day\n for the corresponding mts_symbol, a 'None' is put in place\n \"\"\"\n tm = self.get_tradable_map(trade_day, mts_key=True, mts_symbols = mts_symbol_arr)\n ret = []\n for ms in mts_symbol_arr:\n if ms not in tm.keys() :\n ret.append(None)\n else :\n ret.append(tm[ms][\"tradable\"])\n return ret\n\n def get_contract_from_symbol(self, mts_symbol_no_N, trade_day, add_prev_day=False, include_spread=True, extra_N=[]):\n \"\"\"\n mts_symbol_no_N: mts_symbol that doesn't have '_N', i.e. WTI\n trade_day: a trading day in YYYYMMDD\n include_spread: if True, includes all spreads within the limit of maxn, \n i.e. if max=2, N0-N1, N0-N2, N1-N2\n if False, no spread is included\n extra_N: list of N beyond the max_N, i.e [6,9,12] for max_N=2 (cannot include spread)\n return: a list of all contracts that matches with the symbol on\n the day, upto max_N defined in self.max_N\n NOTE - since the calendar file has only contracts upto N_6, in order to extend to N_12\n it runs again at half year earlier\n \"\"\"\n assert (not include_spread) or (len(extra_N) == 0)\n # handle the extra_N here\n max_N = self.max_N\n max_NE = max_N if len(extra_N)==0 else max(max_N, np.max(extra_N))\n if len(extra_N) > 1:\n en = np.array(extra_N)\n assert np.min(en[1:]-en[:-1]) > 0\n\n if max_NE > 6:\n assert max_NE <= 12\n self.max_N = 6\n else:\n self.max_N = max_NE\n\n tm = self.get_tradable_map(trade_day, mts_key=True, mts_symbols = [ mts_symbol_no_N ], add_prev_day=add_prev_day)\n assert len(tm.keys()) > 0, 'no contracts found on ' + trade_day + ', a holiday?'\n Ns = []\n Contracts = []\n for ms in tm.keys():\n if not include_spread and ('S' in tm[ms].keys()):\n continue\n symbol = tm[ms]['symbol']\n if symbol == mts_symbol_no_N :\n Ns.append(tm[ms]['N'])\n Contracts.append(tm[ms]['contract_month'])\n nix = np.argsort(Ns)\n Ns = list(np.array(Ns)[nix])\n Contracts = list(np.array(Contracts)[nix])\n\n if max_NE > 6:\n # get a day of 6 months ago and get a list of 6 contracts to append to\n day = trade_day\n year = int(day[:4])\n month = int(day[4:6])\n if month < 7:\n year -= 1\n month += 6\n else:\n month -= 6\n day = '%04d%02d'%(year,month)+day[-2:]\n tdi = mts_util.TradingDayIterator(day)\n day = tdi.begin()\n\n # This is quite a hack - \n # if the current day has just rolled, i.e. N6\n # is a new contract, make sure the dates half \n # year earlier starts from 'N7'\n if np.min(Ns) == 0:\n day = tdi.next(10)\n\n Ns2 = []\n Contracts2 = []\n tm2 = self.get_tradable_map(day, mts_key=True, mts_symbols = [ mts_symbol_no_N ], add_prev_day=True)\n # generate all the contracts\n for ms in tm2.keys() :\n if not include_spread and ('S' in tm2[ms].keys()):\n continue\n symbol = tm2[ms][\"symbol\"]\n if symbol == mts_symbol_no_N :\n Ns2.append(tm2[ms]['N'])\n Contracts2.append(tm2[ms]['contract_month'])\n nix = np.argsort(Ns2)\n Ns2 = list(np.array(Ns2)[nix])\n Contracts2 = list(np.array(Contracts2)[nix])\n \n # populate the Ns\n for con in Contracts2 :\n year = int(con[:4])+1\n con = '%04d'%(year)+con[-2:]\n if con > Contracts[-1]:\n Ns.append(Ns[-1]+1)\n Contracts.append(con)\n\n ix = np.searchsorted(np.array(Ns), max_N)\n assert Ns[ix] == max_N\n ret = Contracts[:ix+1]\n\n # make Ns (the contract in the future) to Ms (the months in the future)\n Ms = np.array(Contracts).astype(int)//100*12+(np.array(Contracts).astype(int)%100)\n Ms = Ms - Ms[0] + Ns[0]\n for en in extra_N:\n if en <= max_N:\n continue\n ix = np.clip(np.searchsorted(np.array(Ms), en),0,len(Ns)-1)\n if Ns[ix] == en:\n ret.append(Contracts[ix])\n\n self.max_N=max_N\n return ret\n\n def get_symbol_contract_from_tradable(self, tradable, trade_day = None, is_mts_symbol=False, add_prev_day=False) :\n \"\"\"\n return mts_symbol, symbol and contract_month\n \"\"\"\n\n max_N0 = self.max_N\n max_N = max_N0\n # for MTS non-spread symbols, N can be entertained\n if is_mts_symbol and len(tradable.split('_')) == 2:\n sym = tradable.split('_')[0]\n N = tradable.split('_')[1]\n assert N[0] == 'N', 'unknown format of MTS symbol: ' + tradable\n n = int(N[1:])\n assert n >= 0 and n <= 12, 'N out of range: ' + tradable\n if n > self.max_N:\n if n <= 6:\n max_N = 6\n else:\n if trade_day is None :\n trade_day = datetime.datetime.now().strftime('%Y%m%d')\n con = self.get_contract_from_symbol(sym, trade_day, add_prev_day=add_prev_day, include_spread=False, extra_N=[n])\n return tradable, sym, con[-1]\n\n self.max_N = max_N\n tinfo = self.get_tinfo(tradable, trade_day, is_mts_symbol=is_mts_symbol,add_prev_day=add_prev_day)\n self.max_N = max_N0\n return tinfo['mts_symbol'], tinfo['symbol'], tinfo['contract_month']\n\n def get_mts_symbol_from_tt_venue(self, tt_venue_arr, trade_day, tt_venue_map_cfg='config/venue_map.cfg', N=1) :\n ttvm = self._load_tt_venue_map(tt_venue_map_cfg)\n tm = self.get_tradable_map(trade_day, mts_key=True)\n ret = []\n for ms in tm.keys() :\n ttv = ttvm[tm[ms][\"venue\"]]\n if tt_venue_arr is None or ttv in tt_venue_arr :\n if ms[-1] != str(N) :\n continue\n ret.append([tm[ms][\"symbol\"], ttv])\n return ret\n\n def get_mts_symbol_from_mts_venue(self, mts_venue_arr, trade_day) :\n tm = self.get_tradable_map(trade_day, mts_key=True)\n ret = []\n for ms in tm.keys() :\n venue = tm[ms][\"venue\"]\n if venue in mts_venue_arr :\n ret.append(ms)\n return ret\n\n def get_mts_symbol_from_field(self, trade_day, field_values, field_name) :\n tm = self.get_tradable_map(trade_day, mts_key=True)\n ret = []\n for ms in tm.keys() :\n if field_name not in tm[ms].keys() :\n continue\n val = tm[ms][field_name]\n if val in field_values: \n ret.append(ms)\n return ret\n\n def getSubscriptionList(self, mts_cfg, trade_day) :\n # read \"MTSVenue\" and \"MTSSymbol\" from config and return a list of mts_symbol\n # as subscription list\n sub_venue0 = mts_cfg.listSubKeys('MTSVenue')\n sub_venue = []\n for v in sub_venue0 :\n if len(mts_cfg.getArr('MTSVenue.'+v)) > 0 :\n sub_venue.append(v)\n\n sub_symbol0 = mts_cfg.listSubKeys('MTSSymbol')\n sub_symbol = []\n for s in sub_symbol0 :\n if len(mts_cfg.getArr('MTSSymbol.'+s)) > 0 :\n sub_symbol.append(s)\n\n sub_symbol= set(self.get_mts_symbol_from_field(trade_day, sub_symbol, 'symbol'))\n sub_symbol.update(self.get_mts_symbol_from_mts_venue(sub_venue, trade_day))\n return sub_symbol\n\n def _load_tt_venue_map(self, tt_venue_map_cfg) :\n vm = {}\n try :\n with open(tt_venue_map_cfg, \"r\") as f :\n while True :\n l = f.readline()\n if len(l) ==0 :\n break\n l = l.strip()\n if l[0] == '#' :\n continue\n la = l.split('=')\n if len(la) == 2 :\n vm[la[0].strip()] = la[1].strip()\n except :\n traceback.print_exc()\n print (\"failed to load tt venue map!\")\n return vm\n\n def _get_assets_root(self) :\n if self.assets_root is None :\n try :\n self.assets_root = gen_asset_root(self.xml_path, self.assets_xml)\n except :\n traceback.print_exc()\n raise RuntimeError(\"Cannot get symbol map from \" + self.xml_path + \", \" + self.assets_xml)\n\n\nclass FXMap :\n def __init__(self, fx_filename='/home/mts/run/config/symbol/fx_1700.txt'):\n \"\"\"\n days, utcs: array of yyyymmdd (utc) of the days of rates\n syms: array of symbols of columns of rates\n rates: shape [ndays,nfx] rates x, where x is number of USD needed to for 1 FX\n \"\"\"\n self.fn = fx_filename\n self.syms, self.days, self.utcs, self.rates = self._load()\n\n def _load(self):\n \"\"\"load historical FX from file into fxdict, i.e. fx_1500.txt\n File format:\n Header:\n trade_date,AUD,BRL,CAD,CHF,CLP,CNH,CNY,COP,CZK,DKK,EUR,GBP,HKD,HUF,IDR,ILS,INR,ISK,JPY,KRW,MXN,MYR,NOK,NZD,PHP,PLN,RUB,SAR,SEK,SGD,THB,TRY,TWD,ZAR\n Body:\n 2007-02-28,0.7879,,,,,,,,,,1.3231,1.9636,,,,,,,,,,,,0.7016,,,,,,,,,,\n \"\"\"\n syms = subprocess.check_output(['head','-1',self.fn]).decode().replace('\\r','').replace('\\n','').split(',')[1:]\n rates = np.genfromtxt(self.fn, delimiter=',',skip_header=1,dtype='str')\n days = []\n utcs = []\n for d in rates[:,0]:\n dt = datetime.datetime.strptime(d, '%Y-%m-%d')\n days.append(dt.strftime('%Y%m%d'))\n utcs.append(int(dt.strftime('%s'))+17*3600) # utc at 17:00 of the day\n\n rates[np.nonzero(rates=='')]='1'\n rates=rates[:,1:].astype(float)\n return np.array(syms), np.array(days), np.array(utcs), rates\n\n def get(self, sym, day, use_prev_day=True, default=None):\n \"\"\"\n sym: str, i.e. 'EUR', 'GBP'\n day: yyyymmdd\n use_prev_day: use previous day if day is not found\n default: if sym not found, throw if None, otherwise use the default\n \"\"\"\n six = np.nonzero(self.syms==sym)[0]\n if len(six) == 0:\n if default is not None:\n return default\n raise RuntimeError('unknown FX: %s'%(sym))\n six=six[0]\n\n dix = max(np.searchsorted(self.days, str(int(day)+1))-1,0)\n if self.days[dix] != day:\n if not use_prev_day:\n raise RuntimeError('%s not found on %s'%(sym,day))\n return self.rates[dix,six]\n\n def get_by_utc(self, sym, utc, use_prev_day=True, default=None):\n six = np.nonzero(self.syms==sym)[0]\n if len(six) == 0:\n if default is not None:\n return default\n raise RuntimeError('unknown FX: %s'%(sym))\n six=six[0]\n\n dix = max(np.searchsorted(self.utcs, utc+1)-1,0)\n if not use_prev_day:\n utc0=self.utcs[dix]\n ymd0 = datetime.datetime.fromtimestamp(utc0).strftime('%Y%m%d')\n ymd = datetime.datetime.fromtimestamp(utc).strftime('%Y%m%d')\n if ymd != ymd0:\n raise RuntimeError('%s not found on %s'%(sym,ymd))\n return self.rates[dix,six]\n\n\n\n","sub_path":"mts/python/symbol_map.py","file_name":"symbol_map.py","file_ext":"py","file_size_in_byte":35213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"344080463","text":"from random import randint\nfrom time import sleep\n\n\nclass Jogo:\n def __init__(self):\n self.numero = randint(0, 10)\n self.entrada = int(input())\n\n @staticmethod\n def easy():\n print('\\nVocê escolheu o modo fácil! Vamos jogar.')\n sleep(1)\n print('Pensando no número que quero que você adivinhe...')\n sleep(3)\n print('Escolhi um número!')\n sleep(1)\n numero = randint(0, 10)\n while True:\n try:\n entrada = int(input('De 0 a 10, que número estou pensando?\\n'))\n except ValueError:\n print('\\nApenas números de 0 a 10! Tente de novo!')\n sleep(1)\n else:\n if entrada < 0 or entrada > 10:\n print('\\nO número tem que ser entre 0 e 10. Escolha outra vez!\\n')\n sleep(1)\n continue\n else:\n if entrada == numero:\n print('Parabéns, você venceu!')\n break\n elif entrada < numero:\n print('\\nErrado, o número é maior.\\n')\n sleep(1)\n continue\n else:\n print('\\nErrado, o número é menor\\n')\n sleep(1)\n continue\n\n @staticmethod\n def medium():\n print('\\nVocê escolheu o módo médio. Vamos lá!')\n sleep(1)\n print('Pensando no número que quero que você adivinhe...')\n sleep(3)\n print('Escolhi um número.')\n sleep(1)\n numero = randint(0, 10)\n while True:\n try:\n entrada = int(input('\\nDe 0 a 10, que numero estou pensando?\\n'))\n except ValueError:\n print('Apenas números entre 0 e 10! Tente de novo!')\n else:\n if entrada < 0 or entrada > 10:\n print('O número tem que ser entre 0 e 10! Escolha de novo!')\n sleep(1)\n continue\n else:\n if entrada == numero:\n print('Parabéns, você venceu sem nenhuma dica!')\n break\n else:\n print('\\nNúmero errado. Tente de novo!\\n')\n sleep(1)\n continue\n\n @staticmethod\n def hard():\n print('\\nVocê escolheu o modo difícil. Boa sorte!')\n sleep(1)\n print('Pensando no número que quero que você adivinhe...')\n sleep(3)\n while True:\n print('Escolhi um número!')\n sleep(1)\n try:\n entrada = int(input('\\nDe 0 a 10, que número estou pensando?\\n'))\n numero = randint(0, 10)\n except ValueError:\n print('Apenas números entre 0 e 10! Tente de novo!\\n')\n else:\n if entrada < 0 or entrada > 10:\n print('O número tem que ser entre 0 e 10. Escolha outra vez!\\n')\n sleep(1)\n continue\n else:\n if entrada == numero:\n print('Foi difícil, mas você ganhou! Parabéns!')\n break\n else:\n print('\\nNumero errado. Dessa vez não vai ser fácil!\\n')\n sleep(1)\n continue\n","sub_path":"jogoClasses.py","file_name":"jogoClasses.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"606219446","text":"import time\nimport json\nfrom urlparse import urlparse\n\nfrom google.appengine.api import urlfetch\n\nimport config\n\n# pull down the base info for the repo\ndef repo_base(url):\n\ttry:\n\t\t# parse the url and build a normalized github URL\n\t\tparts = urlparse(url)\n\t\turl = \"https://%s/%s\" % (config.github_url.strip('/'), parts[2].strip('/'))\n\t\t\n\t\t# use the path to make an API GET for the repo JSON\n\t\trepo = json.loads(\n\t\t\turlfetch.fetch(\"https://%s/%s/%s\" % (\n\t\t\t\tconfig.github_api_url.strip('/'),\n\t\t\t\t'repos',\n\t\t\t\tparts[2].strip('/')\n\t\t\t), deadline=5).content\n\t\t)\n\n\t\tif 'name' not in repo:\n\t\t\traise Exception(\"A valid Github repository was not found using that URL.\")\n\n\t\t# build and return the response\n\t\tresponse = {'response': 'success', 'result': {'repo': repo}}\n\t\treturn response\n\n\texcept Exception as ex:\n\t\t# build and return the failure\n\t\tresponse = {'response': 'fail', 'result': {'message': \"Project was not added. %s\" % ex} }\n\t\treturn response\n\ndef repo_sync_contents(project):\n\ttry:\n\t\t# parse the url and build a normalized github URL\n\t\tparts = urlparse(project.url)\n\t\turl = \"https://%s/%s\" % (config.github_url.strip('/'), parts[2].strip('/'))\n\t\t\n\t\t# use the path to make an API GET for the repo JSON\n\t\tcontents = json.loads(\n\t\t\turlfetch.fetch(\"https://%s/%s/%s/%s/%s\" % (\n\t\t\t\tconfig.github_api_url.strip('/'),\n\t\t\t\t'repos',\n\t\t\t\tparts[2].strip('/'), # repo name\n\t\t\t\t'contents',\n\t\t\t\t'utterio'\n\t\t\t), deadline=5).content\n\t\t)\n\n\t\t# check for required files\n\t\tcheck = {'README.md': 0, 'install.sh': 0, 'icon.png': 0}\n\t\tfor file in contents:\n\t\t\tif file['name'] == \"README.md\":\n\t\t\t\tproject.readme_url = file['download_url']\n\t\t\t\tproject.readme_link = file['html_url']\n\t\t\t\tcheck['README.md'] = 1\n\t\t\tif file['name'] == \"install.sh\":\n\t\t\t\tproject.install_url = file['download_url']\n\t\t\t\tproject.install_link = file['html_url']\n\t\t\t\tcheck['install.sh'] = 1\n\t\t\tif file['name'] == \"icon.png\":\n\t\t\t\tproject.icon_url = file['download_url']\n\t\t\t\tproject.icon_link = file['html_url']\n\t\t\t\tcheck['icon.png'] = 1\n\n\t\t# do a pass to build missing files string\n\t\tmissing = \"\"\n\t\tfor key,value in check.items():\n\t\t\tif not value:\n\t\t\t\tmissing = \"%s%s, \" % (missing, key)\n\t\tmissing = missing.strip(', ')\n\n\t\t# update the repo\n\t\tproject.put()\n\n\t\t# build the response object\n\t\tresponse = {'response': \"success\", 'result': {'message': ''}}\n\n\t\t# build the appropriate message\t\t\t\n\t\tif missing == \"\":\n\t\t\t# build and return the response\n\t\t\tresponse['result']['message'] = \"A complete Utter.io configuration was found!\"\n\t\telse:\n\t\t\tresponse['response'] = \"fail\"\n\t\t\tresponse['result']['message'] = \"The repository needs the following files added to the utterio directory: %s.\" % missing\n\n\t\treturn response\n\n\texcept Exception as ex:\n\t\t# build and return the failure\n\t\tresponse = {'response': \"fail\", 'result': {'message': \"This repository needs an utterio directory added to it.\"} }\n\t\treturn response\n\n\n","sub_path":"lib/github/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"91698984","text":"import numpy as np\r\nimport pandas as pd\r\nfrom scipy.stats import stats\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn import metrics\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\nfrom statistics import mode\r\n\r\n\r\ndef case_submission_year_range(df):\r\n df['CASE_SUBMITTED_YEAR_RANGE'] = np.nan\r\n for i in range(len(df['CASE_SUBMITTED_YEAR'])):\r\n if int(df['CASE_SUBMITTED_YEAR'][i]) <= 2012:\r\n df.loc[i, 'CASE_SUBMITTED_YEAR_RANGE'] = 'BEFORE 2012'\r\n if int(df['CASE_SUBMITTED_YEAR'][i]) > 2012:\r\n df.loc[i, 'CASE_SUBMITTED_YEAR_RANGE'] = 'AFTER 2012'\r\n\t\t\t\r\ndef prevailing_wage(df):\r\n df['PREVAILING_WAGE_RANGE'] = np.nan\r\n for i in range(len(df['PREVAILING_WAGE'])):\r\n if int(df['PREVAILING_WAGE'][i]) <= 20000:\r\n df.loc[i, 'PREVAILING_WAGE_RANGE'] = '0 - 20000'\r\n if int(df['PREVAILING_WAGE'][i]) > 20000 and int(df['PREVAILING_WAGE'][i]) <= 50000:\r\n df.loc[i, 'PREVAILING_WAGE_RANGE'] = '20000 - 50000'\r\n if int(df['PREVAILING_WAGE'][i]) > 50000 and int(df['PREVAILING_WAGE'][i]) <= 120000:\r\n df.loc[i, 'PREVAILING_WAGE_RANGE'] = '50000 - 120000'\r\n if int(df['PREVAILING_WAGE'][i]) > 120000 and int(df['PREVAILING_WAGE'][i]) <= 250000:\r\n df.loc[i, 'PREVAILING_WAGE_RANGE'] = '120000 - 250000'\r\n if int(df['PREVAILING_WAGE'][i]) > 250000:\r\n df.loc[i, 'PREVAILING_WAGE_RANGE'] ='>250000'\r\n\r\ndef merge_labels(df):\r\n '''Merges labels like CERTIFIEDWITHDRAWN in the dataset into CERTIFIED class, and REJECTED, INVALIDATED with DENIED class\r\n Here we are transforming multiclass dataset into binary classification data with labels CERTIFIED and DENIED'''\r\n df['CASE_STATUS'] = df['CASE_STATUS'].replace(['CERTIFIEDWITHDRAWN'], ['CERTIFIED'])\r\n df['CASE_STATUS'] = df['CASE_STATUS'].replace(['REJECTED'], ['DENIED'])\r\n df['CASE_STATUS'] = df['CASE_STATUS'].replace(['INVALIDATED'], ['DENIED'])\r\n labels = df['CASE_STATUS'].unique()\r\n #print(labels)\r\n\r\n\r\ndef fill_nan_values(df):\r\n '''The dataset consists of many nan values. These are replaced by the mode for various columns like EMPLOYER_NAME,\r\n EMPLOYER_STATE, FULL_TIME_POSITION ,PW_UNIT_OF_PAY ,PW_SOURCE, PW_SOURCE_YEAR, H-1B_DEPENDENT, WILLFUL_VIOLATOR. For the column\r\n PREVAILING_WAGE we replace the nan columns with the mean value of the wage data. Also, if the SOC_NAME () is not available,\r\n we replace it with hardcoded value Others'''\r\n\r\n df['EMPLOYER_NAME'] = df['EMPLOYER_NAME'].fillna(df['EMPLOYER_NAME'].mode()[0])\r\n df['EMPLOYER_STATE'] = df['EMPLOYER_STATE'].fillna(df['EMPLOYER_STATE'].mode()[0])\r\n df['FULL_TIME_POSITION'] = df['FULL_TIME_POSITION'].fillna(df['FULL_TIME_POSITION'].mode()[0])\r\n df['PW_UNIT_OF_PAY'] = df['PW_UNIT_OF_PAY'].fillna(df['PW_UNIT_OF_PAY'].mode()[0])\r\n df['PW_SOURCE'] = df['PW_SOURCE'].fillna(df['PW_SOURCE'].mode()[0])\r\n df['PW_SOURCE_YEAR'] = df['PW_SOURCE_YEAR'].fillna(df['PW_SOURCE_YEAR'].mode()[0])\r\n df['H-1B_DEPENDENT'] = df['H-1B_DEPENDENT'].fillna(df['H-1B_DEPENDENT'].mode()[0])\r\n df['WILLFUL_VIOLATOR'] = df['WILLFUL_VIOLATOR'].fillna(df['WILLFUL_VIOLATOR'].mode()[0])\r\n\r\n\r\n df['SOC_NAME'] = df.SOC_NAME.replace(np.nan, 'Others', regex=True)\r\n\r\n df.PREVAILING_WAGE.fillna(df.PREVAILING_WAGE.mean(), inplace=True)\r\n\r\n\r\ndef classify_employer(df):\r\n # Check if the employer name is a 'university'. Since employers with university in their name have more chances of visa approval\r\n df['UNIV_EMPLOYER'] = np.nan\r\n df['EMPLOYER_NAME'] = df['EMPLOYER_NAME'].str.lower()\r\n df.loc[df['EMPLOYER_NAME'].str.contains('university'), 'UNIV_EMPLOYER'] = 'university'\r\n df['UNIV_EMPLOYER'] = df.UNIV_EMPLOYER.replace(np.nan, 'non university', regex=True)\r\n\r\n # Broadly classifying the occupations for people filing the visa petition\r\n df['OCCUPATION'] = np.nan\r\n df['SOC_NAME'] = df['SOC_NAME'].str.lower()\r\n\r\n df.loc[df['SOC_NAME'].str.contains(\r\n 'computer|graphic|web|developer|programmer|software|it|database|analyst'), 'OCCUPATION'] = 'IT Industry'\r\n df.loc[df['SOC_NAME'].str.contains(\r\n 'business|managers|planners|management|public relation|executives|supervisor|curator|human resources'), 'OCCUPATION'] = 'Management'\r\n df.loc[df['SOC_NAME'].str.contains('math|statistic|stats'), 'OCCUPATION'] = 'Maths Department'\r\n df.loc[df['SOC_NAME'].str.contains('promotion|market|advertis'), 'OCCUPATION'] = 'Marketing Department'\r\n df.loc[df['SOC_NAME'].str.contains('accountant|finance|acc'), 'OCCUPATION'] = 'Finance Department'\r\n df.loc[df['SOC_NAME'].str.contains(\r\n 'education|prof|teacher|linguist|teach|counsel|coach'), 'OCCUPATION'] = 'Education Department'\r\n df.loc[df['SOC_NAME'].str.contains(\r\n 'scientist|science|psychia|doctor|surgeon|biolog|clinical reasearch|physician|dentist|health'), 'OCCUPATION'] = 'Advance Sciences'\r\n df.loc[\r\n df['SOC_NAME'].str.contains(\r\n 'engineer|technician|surveyor|architec'), 'OCCUPATION'] = 'Engineering and Architecture'\r\n df['OCCUPATION'] = df.OCCUPATION.replace(np.nan, 'Others', regex=True)\r\n\r\ndef preprocessingTrainingdata(user_input):\r\n print(\"Pre Processing data for training set\")\r\n if(user_input=='1' or user_input=='3' or user_input=='2'):\r\n df_train = pd.read_csv('File 1 - H1B Dataset.csv',encoding=\"ISO-8859-1\")\r\n\r\n merge_labels(df_train)\r\n\r\n #clean data by filling the NAN data with appropriate values\r\n fill_nan_values(df_train)\r\n prevailing_wage(df_train)\r\n case_submission_year_range(df_train)\r\n \r\n #Create new column OCCUPATION to broadly classify the occupations for H1B petition filers.\r\n #Also creating column UNIV_EMPLOYER for checking if the emplyer name is a university\r\n classify_employer(df_train)\r\n\r\n class_mapping = {'CERTIFIED': 0, 'DENIED': 1}\r\n df_train[\"CASE_STATUS\"] = df_train[\"CASE_STATUS\"].map(class_mapping)\r\n\r\n#Creating a copy of dataset for prediction\r\n df1_train_set = df_train[\r\n ['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']].copy()\r\n\r\n df1_train_set[['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']] = df1_train_set[\r\n ['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']].apply(lambda x: x.astype('category'))\r\n\r\n #print(df1_train_set.head())\r\n\r\n X = df1_train_set.loc[:, 'FULL_TIME_POSITION':'WORKSITE_STATE']\r\n Y = df1_train_set.CASE_STATUS\r\n\r\n seed = 5\r\n X_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=0.3, random_state=seed)\r\n #print(X_train.isnull().sum())\r\n\r\n X_train_encode = pd.get_dummies(X_train)\r\n X_val_encode = pd.get_dummies(X_validation)\r\n\r\n train_X = X_train_encode.values\r\n train_y = Y_train.values\r\n\r\n val_x = X_val_encode.values\r\n val_y = Y_validation.values\r\n print(\"Pre Processing is completed for training set\")\r\n return train_X,train_y,val_x,val_y\r\n\r\ndef preprocessingTestingdata(user_input):\r\n print(\"Pre Processing data for test set\")\r\n if(user_input=='1' or user_input=='3' or user_input=='2'):\r\n df_test = pd.read_csv('File 2 - H1B Dataset.csv',encoding=\"ISO-8859-1\")\r\n \r\n merge_labels(df_test)\r\n fill_nan_values(df_test)\r\n prevailing_wage(df_test)\r\n case_submission_year_range(df_test)\r\n classify_employer(df_test)\r\n df1_test_set = df_test[\r\n ['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']].copy()\r\n\r\n df1_test_set[['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']] = df1_test_set[\r\n ['FULL_TIME_POSITION', 'PREVAILING_WAGE_RANGE', 'CASE_SUBMITTED_YEAR_RANGE', 'UNIV_EMPLOYER', 'OCCUPATION', 'WORKSITE_STATE',\r\n 'CASE_STATUS']].apply(lambda x: x.astype('category'))\r\n class_mapping = {'CERTIFIED': 0, 'DENIED': 1}\r\n df1_test_set[\"CASE_STATUS\"] = df1_test_set[\"CASE_STATUS\"].map(class_mapping)\r\n\r\n X_test = df1_test_set.loc[:, 'FULL_TIME_POSITION':'WORKSITE_STATE']\r\n Y_test = df1_test_set.CASE_STATUS\r\n\r\n X_test_encode = pd.get_dummies(X_test)\r\n testX = X_test_encode.values\r\n\t\r\n testY = Y_test.values\r\n print(\"Pre Processing is completed for test set\")\r\n return testX, testY","sub_path":"DataPreProcessing.py","file_name":"DataPreProcessing.py","file_ext":"py","file_size_in_byte":8679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"102658962","text":"\"\"\"\n Use the same techniques such as (but not limited to):\n 1) Sockets\n 2) File I/O\n 3) raw_input()\n\n from the OSINT HW to complete this assignment. Good luck!\n\"\"\"\n\nimport socket\n\nhost = \"cornerstoneairlines.co\" # IP address here\nport = 45 # Port here\n\n# opens connection and issues command, expects command to start with \";\"\ndef execute_cmd(cmd):\n # Establish socket connection\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n data = s.recv(1024) # Receives 1024 bytes from IP/Port\n s.send(cmd + \"\\n\")\n data = s.recv(1024)\n return data\n\n# shell logic\ndef shell():\n path = \"/\"\n while(True):\n cmd = raw_input(path.strip() + \"> \").strip()\n if (cmd == \"exit\"):\n break\n elif (cmd.startswith(\"cd\")):\n pwd = execute_cmd(\";cd \" + path + \";\" + cmd + \";pwd\").strip()\n if (pwd != \"\"):\n path = pwd\n else:\n print(execute_cmd(\";cd \" + path + \";\" + cmd).strip())\n\n# reads in remote file using cat command and then writes it to the local path\ndef pull(remote, local):\n file = execute_cmd(\";cat \" + remote)\n open(local, \"w+\").write(file)\n\n# prints commands that are available\ndef help():\n print(\n \"\"\"1) shell: Drop into an interactive shell and allow users to gracefully `exit`\n 2) pull : Download files\n 3) help: Shows this help menu\n 4) quit: Quit the shell\"\"\")\n\nif __name__ == '__main__':\n while(True):\n cmd = raw_input(\"> \").strip()\n if (cmd == \"shell\"):\n shell()\n elif (cmd.startswith(\"pull\")):\n args = cmd.split()\n if (len(args) == 3):\n pull(args[1], args[2])\n else:\n print(\"Pull takes two arguments\")\n elif (cmd == \"quit\"):\n break\n else:\n help()","sub_path":"week/4/writeup/stub.py","file_name":"stub.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"349079128","text":"import requests\n\n\ndef main():\n\n with requests.Session() as s:\n\n r = s.post(\"http://127.0.0.1:5000/login\", data={\n \"username\": \"test\",\n \"password\": \"test\"\n }\n )\n\n print(r.text)\n\n for x in range(20, 100):\n\n r = s.post(\"http://127.0.0.1:5000/create_puzzle\", data={\n \"title\": \"The best puzzle \" + str(x),\n \"hint_1\": \"one\",\n \"answer_1\": \"two\",\n \"hint_2\": \"three\",\n \"answer_2\": \"four\",\n \"hint_3\": \"five\",\n \"answer_3\": \"six\",\n \"hint_4\": \"seven\",\n \"answer_4\": \"eight\",\n \"hint_5\": \"nine\",\n \"answer_5\": \"ten\",\n \"hint_6\": \"eleven\",\n \"answer_6\": \"twelve\",\n \"hint_7\": \"thirteen\",\n \"answer_7\": \"fourteen\",\n \"hint_8\": \"fifteen\",\n \"answer_8\": \"sixteen\",\n \"hint_9\": \"seventeen\",\n \"answer_9\": \"eighteen\",\n \"hint_10\": \"nineteen\",\n \"answer_10\": \"twenty\"\n })\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"util/fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"393498689","text":"import numpy as np \nnp.random.seed(1337)\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport matplotlib.pyplot as plt\n\n# create some data\nX = np.linspace(-1, 1, 200)\nnp.random.shuffle(X) # randomize the data\nY = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))\n# plot data\n# plt.scatter(X, Y)\n# plt.show()\n\nX_train, Y_train = X[:160], Y[:160] # train 前 160 data points\nX_test, Y_test = X[160:], Y[160:] # test 后 40 data points\n\n#build model\nmodel= Sequential()\nmodel.add(Dense(output_dim=1,input_dim=1))\n#choose loss function\nmodel.compile(loss='mse',optimizer='sgd')\n\n#train\nprint(\"training__________________________________\")\nfor step in range(301):\n cost = model.train_on_batch(X_train,Y_train)\n if step %100==0:\n #maybe str()\n print('traincost',cost)\n\n\n#test\nprint(\"test__________________________________\")\ncost =model.evaluate(X_test,Y_test,batch_size=40)\nW,b = model.layers[0].get_weights()\nprint('Weights=', W, '\\nbiases=', b)\n\n# plotting the prediction\nY_pred = model.predict(X_test)\nplt.scatter(X_test, Y_test)\nplt.plot(X_test, Y_pred)\nplt.show()\n","sub_path":"HW2-LSTM/keras_practice/keras_regressor_practice.py","file_name":"keras_regressor_practice.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"612846896","text":"# Copyright (C) 2009, Hyves (Startphone Ltd.)\n#\n# This module is part of the Concurrence Framework and is released under\n# the New BSD License: http://www.opensource.org/licenses/bsd-license.php\n\n#TODO write timeout\n\nfrom __future__ import with_statement\n\nimport logging\nimport urlparse\nimport httplib\nimport traceback\nimport rfc822\n\nfrom concurrence import Tasklet, Message, Channel, TimeoutError, __version__\nfrom concurrence.io import Socket, Buffer, BufferedStream\nfrom concurrence.containers import ReorderQueue\nfrom concurrence.timer import Timeout\nfrom concurrence.http import HTTPError, HTTPParser\n\nSERVER_ID = \"Concurrence-Http/%s\" % __version__\n\nclass WSGIErrorStream(object):\n def write(self, s):\n logging.error(s)\n\n def writelines(self, s):\n assert False, 'TODO'\n\n def flush(self):\n assert False, 'TODO'\n\nclass WSGIRequest(object):\n log = logging.getLogger('WSGIRequest')\n\n def __init__(self, environ):\n self.environ = environ\n\n self.environ['SCRIPT_NAME'] = '' #TODO\n\n #add wsgi stuff\n self.environ['wsgi.url_scheme'] = 'http'\n self.environ['wsgi.multiprocess'] = False\n self.environ['wsgi.multithread'] = True\n self.environ['wsgi.run_once'] = False\n self.environ['wsgi.version'] = (1, 0)\n\n #wsgi complience\n if 'HTTP_CONTENT_LENGTH' in self.environ:\n self.environ['CONTENT_LENGTH'] = self.environ['HTTP_CONTENT_LENGTH']\n\n if 'HTTP_CONTENT_TYPE' in self.environ:\n self.environ['CONTENT_TYPE'] = self.environ['HTTP_CONTENT_TYPE']\n\n #setup required wsgi streams\n #self.environ['wsgi.input'] = WSGIInputStream(self, reader)\n self.environ['wsgi.errors'] = WSGIErrorStream()\n\n if not 'HTTP_HOST' in self.environ:\n if self.environ['HTTP_VERSION'] == 'HTTP/1.0':\n #ok in version 1.0, TODO what should host in wsgi environ be?\n host = 'localhost'\n else:\n raise HTTPError('Host header field is required in HTTP version > 1.0')\n else:\n host = self.environ['HTTP_HOST']\n\n if ':' in host:\n host, port = host.split(':')\n else:\n host, port = host, 80\n\n self.environ['SERVER_NAME'] = host\n self.environ['SERVER_PORT'] = port\n self.environ['SERVER_PROTOCOL'] = self.environ['HTTP_VERSION']\n\n self.response_headers = []\n self.response_status = httplib.OK\n self.response_exc_info = None\n\n #print self.environ\n\n def start_response(self, status, response_headers, exc_info = None):\n self.response_status = status\n self.response_headers = response_headers\n self.response_exc_info = exc_info\n\n @property\n def uri(self):\n return self.environ['REQUEST_URI']\n\n @property\n def version(self):\n return self.environ['HTTP_VERSION']\n\nclass HTTPConnection(object):\n\n def __init__(self, server, client_socket):\n self._server = server\n self._stream = BufferedStream(client_socket)\n #print 'new con'\n\n def _write_response(self, version, status, headers, response):\n\n if version == 'HTTP/1.0':\n chunked = False\n else:\n chunked = True\n\n headers.append(('Date', rfc822.formatdate()))\n headers.append(('Server', SERVER_ID))\n\n if chunked:\n headers.append(('Transfer-Encoding', 'chunked'))\n else:\n headers.append(('Content-length', str(len(response))))\n response = ''.join(response)\n\n with self._stream.get_writer() as writer:\n writer.clear()\n writer.write_bytes(\"%s %s\\r\\n\" % (version, status))\n writer.write_bytes('\\r\\n'.join([\"%s: %s\" % (k, v) for k, v in headers]))\n writer.write_bytes(\"\\r\\n\\r\\n\")\n\n if chunked:\n for chunk in response:\n writer.write_bytes(\"%x;\\r\\n\" % len(chunk))\n writer.write_bytes(chunk)\n writer.write_bytes(\"\\r\\n\")\n writer.write_bytes(\"0\\r\\n\\r\\n\")\n else:\n writer.write_bytes(response)\n\n writer.flush()\n\n def _read_request(self):\n\n with self._stream.get_reader() as reader:\n reader.fill() #initial fill\n parser = HTTPParser(reader.buffer)\n while True:\n #parse the buffer\n if parser.parse():\n break #ok\n else:\n #need more data from socket, could not parse request with data currently in buffer\n reader.append() \n return WSGIRequest(parser.environ)\n\n def _handle_request(self):\n request = self._read_request()\n response = self._server.handle_request(request)\n self._write_response(request.version, request.response_status, request.response_headers, response) \n if request.version == 'HTTP/1.0':\n self._close()\n else:\n self._stream._stream.readable.notify(self.handle, 10)\n\n def _close(self):\n self._stream.close()\n\n def handle(self, has_timedout = False):\n if has_timedout:\n self._stream.close()\n else:\n Tasklet.defer(self._handle_request)\n\nclass WSGIServer(object):\n \"\"\"A HTTP/1.1 Web server with WSGI application interface.\n\n Usage::\n\n def hello_world(environ, start_response):\n start_response(\"200 OK\", [])\n return [\"Hello, world!\"]\n\n server = WSGIServer(hello_world)\n server.serve(('localhost', 8080))\n \"\"\"\n log = logging.getLogger('WSGIServer')\n\n def __init__(self, application, request_log_level = logging.DEBUG):\n \"\"\"Create a new WSGIServer serving the given *application*. Optionally\n the *request_log_level* can be given. This loglevel is used for logging the requests.\"\"\"\n self._application = application\n self._request_log_level = request_log_level\n\n def internal_server_error(self, environ, start_response):\n \"\"\"Default WSGI application for creating a default `500 Internal Server Error` response on any\n unhandled exception.\n The default response will render a traceback with a text/plain content-type.\n Can be overridden to provide a custom response.\"\"\"\n start_response('500 Internal Server Error', [('Content-type', 'text/plain')])\n return [traceback.format_exc(20)]\n\n def handle_request(self, request):\n \"\"\"All HTTP requests pass trough this method.\n This method provides a hook for logging, statistics and or further processing w.r.t. the *request*.\"\"\"\n try:\n response = self._application(request.environ, request.start_response)\n self.log.log(self._request_log_level, \"%s %s\", request.response_status, request.uri) \n except TaskletExit:\n raise\n except:\n self.log.exception(\"unhandled exception while handling request\")\n response = self.internal_server_error(request.environ, request.start_response)\n return response\n\n def handle_connection(self, client_socket):\n \"\"\"All HTTP connections pass trough this method.\n This method provides a hook for logging, statistics and or further processing w.r.t. the connection.\"\"\"\n HTTPConnection(self, client_socket).handle()\n\n def serve(self, endpoint):\n \"\"\"Serves the application at the given *endpoint*. The *endpoint* must be a tuple (, ).\"\"\"\n server_socket = Socket.server(endpoint)\n for client_socket in server_socket.accept_iter():\n self.handle_connection(client_socket)\n\n\n","sub_path":"lib/concurrence/http/server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":7710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502396290","text":"# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom pathlib import PurePath\nfrom textwrap import dedent\nfrom typing import List, Optional\n\nfrom pants.backend.python.lint.pylint.rules import PylintFieldSet, PylintFieldSets\nfrom pants.backend.python.lint.pylint.rules import rules as pylint_rules\nfrom pants.backend.python.target_types import PythonInterpreterCompatibility, PythonLibrary\nfrom pants.backend.python.targets.python_library import PythonLibrary as PythonLibraryV1\nfrom pants.base.specs import FilesystemLiteralSpec, OriginSpec, SingleAddress\nfrom pants.build_graph.build_file_aliases import BuildFileAliases\nfrom pants.core.goals.lint import LintResult\nfrom pants.engine.addresses import Address\nfrom pants.engine.fs import FileContent\nfrom pants.engine.legacy.graph import HydratedTargets\nfrom pants.engine.rules import RootRule\nfrom pants.engine.selectors import Params\nfrom pants.engine.target import Dependencies, Sources, TargetWithOrigin\nfrom pants.testutil.external_tool_test_base import ExternalToolTestBase\nfrom pants.testutil.option.util import create_options_bootstrapper\n\n\nclass PylintIntegrationTest(ExternalToolTestBase):\n # See http://pylint.pycqa.org/en/latest/user_guide/run.html#exit-codes for exit codes.\n source_root = \"src/python\"\n good_source = FileContent(\n path=f\"{source_root}/good.py\", content=b\"'''docstring'''\\nUPPERCASE_CONSTANT = ''\\n\",\n )\n bad_source = FileContent(\n path=f\"{source_root}/bad.py\", content=b\"'''docstring'''\\nlowercase_constant = ''\\n\",\n )\n\n @classmethod\n def alias_groups(cls) -> BuildFileAliases:\n return BuildFileAliases(targets={\"python_library\": PythonLibraryV1})\n\n @classmethod\n def target_types(cls):\n return [PythonLibrary]\n\n @classmethod\n def rules(cls):\n return (\n *super().rules(),\n *pylint_rules(),\n RootRule(PylintFieldSets),\n RootRule(HydratedTargets),\n )\n\n def make_target_with_origin(\n self,\n source_files: List[FileContent],\n *,\n name: str = \"target\",\n interpreter_constraints: Optional[str] = None,\n origin: Optional[OriginSpec] = None,\n dependencies: Optional[List[Address]] = None,\n ) -> TargetWithOrigin:\n for source_file in source_files:\n self.create_file(source_file.path, source_file.content.decode())\n source_globs = [PurePath(source_file.path).name for source_file in source_files]\n self.create_library(\n path=self.source_root, target_type=PythonLibrary.alias, name=name, sources=source_globs\n )\n # We must re-write the files because `create_library` will have over-written the content.\n for source_file in source_files:\n self.create_file(source_file.path, source_file.content.decode())\n target = PythonLibrary(\n {\n Sources.alias: source_globs,\n Dependencies.alias: dependencies,\n PythonInterpreterCompatibility.alias: interpreter_constraints,\n },\n address=Address(self.source_root, name),\n )\n if origin is None:\n origin = SingleAddress(directory=self.source_root, name=name)\n return TargetWithOrigin(target, origin)\n\n def run_pylint(\n self,\n targets: List[TargetWithOrigin],\n *,\n config: Optional[str] = None,\n passthrough_args: Optional[str] = None,\n skip: bool = False,\n ) -> LintResult:\n args = [\"--backend-packages2=pants.backend.python.lint.pylint\"]\n if config:\n self.create_file(relpath=\"pylintrc\", contents=config)\n args.append(\"--pylint-config=pylintrc\")\n if passthrough_args:\n args.append(f\"--pylint-args='{passthrough_args}'\")\n if skip:\n args.append(f\"--pylint-skip\")\n return self.request_single_product(\n LintResult,\n Params(\n PylintFieldSets(PylintFieldSet.create(tgt) for tgt in targets),\n create_options_bootstrapper(args=args),\n ),\n )\n\n def test_passing_source(self) -> None:\n target = self.make_target_with_origin([self.good_source])\n result = self.run_pylint([target])\n assert result.exit_code == 0\n assert \"Your code has been rated at 10.00/10\" in result.stdout.strip()\n\n def test_failing_source(self) -> None:\n target = self.make_target_with_origin([self.bad_source])\n result = self.run_pylint([target])\n assert result.exit_code == 16 # convention message issued\n assert \"bad.py:2:0: C0103\" in result.stdout\n\n def test_mixed_sources(self) -> None:\n target = self.make_target_with_origin([self.good_source, self.bad_source])\n result = self.run_pylint([target])\n assert result.exit_code == 16 # convention message issued\n assert \"good.py\" not in result.stdout\n assert \"bad.py:2:0: C0103\" in result.stdout\n\n def test_multiple_targets(self) -> None:\n targets = [\n self.make_target_with_origin([self.good_source], name=\"t1\"),\n self.make_target_with_origin([self.bad_source], name=\"t2\"),\n ]\n result = self.run_pylint(targets)\n assert result.exit_code == 16 # convention message issued\n assert \"good.py\" not in result.stdout\n assert \"bad.py:2:0: C0103\" in result.stdout\n\n def test_precise_file_args(self) -> None:\n target = self.make_target_with_origin(\n [self.good_source, self.bad_source], origin=FilesystemLiteralSpec(self.good_source.path)\n )\n result = self.run_pylint([target])\n assert result.exit_code == 0\n assert \"Your code has been rated at 10.00/10\" in result.stdout.strip()\n\n def test_respects_config_file(self) -> None:\n target = self.make_target_with_origin([self.bad_source])\n result = self.run_pylint([target], config=\"[pylint]\\ndisable = C0103\\n\")\n assert result.exit_code == 0\n assert \"Your code has been rated at 10.00/10\" in result.stdout.strip()\n\n def test_respects_passthrough_args(self) -> None:\n target = self.make_target_with_origin([self.bad_source])\n result = self.run_pylint([target], passthrough_args=\"--disable=C0103\")\n assert result.exit_code == 0\n assert \"Your code has been rated at 10.00/10\" in result.stdout.strip()\n\n def test_includes_direct_dependencies(self) -> None:\n self.make_target_with_origin(source_files=[], name=\"transitive_dependency\")\n\n direct_dependency_content = dedent(\n \"\"\"\\\n # No docstring because Pylint doesn't lint dependencies\n\n from transitive_dep import doesnt_matter_if_variable_exists\n\n THIS_VARIABLE_EXISTS = ''\n \"\"\"\n )\n self.make_target_with_origin(\n source_files=[\n FileContent(\n f\"{self.source_root}/direct_dependency.py\", direct_dependency_content.encode()\n )\n ],\n name=\"direct_dependency\",\n dependencies=[Address(self.source_root, \"transitive_dependency\")],\n )\n\n source_content = dedent(\n \"\"\"\\\n '''Code is not executed, but Pylint will check that variables exist and are used'''\n from direct_dependency import THIS_VARIABLE_EXISTS\n\n print(THIS_VARIABLE_EXISTS)\n \"\"\"\n )\n target = self.make_target_with_origin(\n source_files=[FileContent(f\"{self.source_root}/target.py\", source_content.encode())],\n dependencies=[Address(self.source_root, \"direct_dependency\")],\n )\n\n result = self.run_pylint([target])\n assert result.exit_code == 0\n assert \"Your code has been rated at 10.00/10\" in result.stdout.strip()\n\n def test_skip(self) -> None:\n target = self.make_target_with_origin([self.bad_source])\n result = self.run_pylint([target], skip=True)\n assert result == LintResult.noop()\n","sub_path":"src/python/pants/backend/python/lint/pylint/rules_integration_test.py","file_name":"rules_integration_test.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394175329","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom Routine import Routine\nfrom PurchaseOrder import PurchaseOrder\nfrom PurchaseOrder import PurchaseOrderItemRow\nfrom Item import Item\nfrom Stock import Stock\n\n\"\"\"\n from StockDepo import StockDepo\n query = Query()\n query.sql = \"SELECT si.{MinQty}, si.{SupUnit},si.{NormalQty},s.{Qty},s.{ArtCode},i.{MinLevel} \"\n query.sql += \"FROM [SupplierItem] si \"\n query.sql += \"INNER JOIN [Stock] s ON si.{ArtCode} = s.{ArtCode} \"\n query.sql += \"INNER JOIN [Item] i ON i.{Code} = si.{ArtCode} \"\n query.sql += \"WHERE?AND (s.{Qty} < i.{MinLevel} OR s.{Qty} IS NULL) \" # Null in case item was never used yet\n query.sql += \"WHERE?AND si.{SupCode} = s|%s| \" % self.SupCode\n query.sql += \"GROUP BY s.{ArtCode} \"\n if query.open():\n for rec in query:\n stockqty = 0\n if rec.Qty: stockqty = rec.Qty\n # Depends on the stock policy \n if (rec.MinLevel):\n orderqty = rec.MinLevel - stockqty\n elif rec.NormalQty: \n orderqty = rec.NormalQty\n else:\n orderqty = 0\n poir = PurchaseOrderItemRow()\n poir.ArtCode = rec.ArtCode\n poir.Qty = orderqty\n poir.pasteArtCode(self)\n poir.pasteQty(self)\n poir.sumUp(self)\n self.Items.append(poir)\n self.sumUp()\n\"\"\"\n\nclass GenPurchaseOrderRoutine(Routine):\n def getSupplierItems(self, supcode):\n res = {}\n query = Query()\n query.sql = \"SELECT [SupplierItem].{SupItemCode}, [SupplierItem].{Discount1}, [SupplierItem].{Discount2},[SupplierItem].{Discount3},[SupplierItem].{Discount4},[SupplierItem].{Discount5},[SupplierItem].{ArtCode}, [Item].{MinLevel}, [Item].{MaxLevel}, [SupplierItem].{MinQty} FROM [SupplierItem]\"\n query.sql += \" INNER JOIN [Item] ON [Item].{Code} = [SupplierItem].{ArtCode}\"\n query.sql += \" WHERE?AND [SupplierItem].{SupCode} = s|%s| \" % supcode\n query.sql += \" WHERE?AND [SupplierItem].{Default} = i|1| \"\n query.sql += \" WHERE?AND ([Item].{Closed} = i|0| OR [Item].{Closed} IS NULL) \"\n if query.open():\n for rec in query:\n res[rec.ArtCode] = {\"MaxLevel\": rec.MaxLevel, \"MinLevel\": rec.MinLevel, \"MinQty\": rec.MinQty, \"MinQty\": rec.MinQty, \"DeliveryPendingQty\": Item.getDeliveryPendingQty(rec.ArtCode), \"PurchaseOrderPendingQty\": Item.getPurchaseOrderPendingQty(rec.ArtCode), \"Stock\": Stock.getQty(rec.ArtCode), \"Discount1\": rec.Discount1, \"Discount1\": rec.Discount1, \"Discount2\": rec.Discount2, \"Discount3\": rec.Discount3, \"Discount4\": rec.Discount4, \"Discount5\": rec.Discount5, \"SupArtCode\": rec.SupItemCode}\n else:\n message(\"No hay Articulos-Proveedor para generar\")\n return res\n\n def genPurchaseOrder(self, supcode):\n po = PurchaseOrder()\n items = self.getSupplierItems(supcode)\n #alert(items['3'])\n if len(items):\n po.defaults()\n po.SupCode = supcode\n po.pasteSupCode()\n artcodes = items.keys()\n artcodes.sort()\n for artcode in artcodes:\n item = items[artcode]\n #if artcode == \"180-301\": alert(item)\n if item[\"Stock\"] - item[\"DeliveryPendingQty\"] + item[\"PurchaseOrderPendingQty\"] < item[\"MinLevel\"]:\n porow = PurchaseOrderItemRow()\n #if artcode == \"180-301\": alert(\"pegado\")\n porow.ArtCode = artcode\n porow.pasteArtCode(po)\n porow.Qty = item[\"MaxLevel\"] - (item[\"Stock\"] - item[\"DeliveryPendingQty\"] + item[\"PurchaseOrderPendingQty\"])\n if porow.Qty < item[\"MinQty\"]:\n porow.Qty = item[\"MinQty\"]\n porow.pasteQty(po)\n for d in (\"Discount1\",\"Discount2\",\"Discount3\",\"Discount4\",\"Discount5\"):\n porow.fields(d).setValue(item[d])\n porow.pasteAccDiscounts(po)\n porow.SupArtCode = item[\"SupArtCode\"]\n porow.sumUp(po)\n po.Items.append(porow)\n po.sumUp()\n return po\n return None\n \n def run(self):\n spec = self.getRecord()\n if spec.SupCode:\n po = self.genPurchaseOrder(spec.SupCode)\n if po:\n if po.Items.count():\n from PurchaseOrderWindow import PurchaseOrderWindow\n w = PurchaseOrderWindow()\n w.setRecord(po)\n w.open()\n else:\n message(\"No hay faltantes para este proveedor\")\n else:\n query = Query()\n query.sql += \"SELECT {Code} FROM [Supplier]\"\n if query.open():\n for rec in query:\n po = self.genPurchaseOrder(rec.Code)\n if po and po.Items.count():\n if not po.save():\n message(tr(\"Routine terminated without saving results\"))\n rollback()\n return\n \n","sub_path":"standard/routines/GenPurchaseOrderRoutine.py","file_name":"GenPurchaseOrderRoutine.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"159227607","text":"import numpy as np\nimport scipy as np\nfrom operator import le\nimport pso\nimport pso_adv\n\nclass PSO_ANN(object):\n\n def __init__(self, hidden_layers = None, lmbd = 1.0,\n p_size = 20, w = 0.8, c1 = 2, c2 = 2, maxiter = 2000, vmax = 1):\n\n if hidden_layers is None:\n self.hidden_layers = [100]\n else:\n self.hidden_layers = hidden_layers\n\n self.L = 2 + len(self.hidden_layers)\n self.A = [None] * self.L\n self.theta = [None] * (self.L - 1)\n self.delta = [None] * self.L\n self.grad = [None] * self.L\n self.lmbd = lmbd\n\n self.p_size = p_size\n self.w = w\n self.c1 = c1\n self.c2 = c2\n self.maxiter = maxiter\n self.vmax = vmax\n\n @staticmethod\n def _sigma(x):\n return 1.0 / (1 + np.exp(-x))\n\n def _f(self, Theta):\n self.A[0] = self.X\n\n theta_idx = 0\n\n for i in range(self.L - 1):\n theta_shape = (self.layers[i] + 1, self.layers[i + 1])\n theta_len = theta_shape[0] * theta_shape[1]\n self.theta[i] = (Theta[theta_idx : theta_idx + theta_len].\n reshape(theta_shape))\n theta_idx += theta_len\n\n z = np.hstack((\n np.ones((self.A[i].shape[0], 1)),\n self.A[i])).dot(self.theta[i])\n self.A[i + 1] = self._sigma(z)\n\n mJ = (- (self.target * np.log(self.A[-1]) +\n (1 - self.target) * np.log(1 - self.A[-1])).sum()\n + self.lmbd * 0.5 * (Theta ** 2).sum())\n #Theta**2?\n\n# self.delta[-1] = self.A[-1] - self.target\n# for i in range(self.L - 2, 0, -1):\n# self.delta[i] = (self.delta[i + 1].dot(self.theta[i].T[:, 1:]) *\n# self.A[i] * (1 - self.A[i]))\n\n# for i in range(self.L - 1):\n# self.grad[i] = np.vstack((\n# np.ones((1, self.A[i].shape[0])),\n# self.A[i].T)).dot(self.delta[i + 1])\n\n# Grad = np.concatenate(map(lambda x: x.flatten(), self.grad[:-1]))\n# Grad += self.lmbd * Theta\n\n return mJ\n\n def init_theta(self):\n init_thetas = [None] * (self.L - 1)\n for i in range(self.L - 1):\n epsilon = np.sqrt(6.0 / (self.layers[i] + self.layers[i + 1]))\n init_thetas[i] = np.random.mtrand.rand(self.layers[i] + 1,\n self.layers[i + 1]) * 2.0 * epsilon - epsilon\n return np.concatenate(map(lambda x: x.flatten(), init_thetas)) \n\n def fit(self, X, y): \n self.X = X \n target_labels = sorted(list(set(y)))\n #cut the redundant\n labels_count = len(target_labels)\n self.labels_map = dict(zip(target_labels, range(labels_count)))\n self.labels_index_map = dict(zip(range(labels_count), target_labels))\n\n self.target = np.zeros((X.shape[0], labels_count))\n for i, label in enumerate(y):\n self.target[i, self.labels_map[label]] = 1\n\n self.layers = [X.shape[1]]\n self.layers.extend(self.hidden_layers)\n self.layers.append(labels_count)\n \n# self.result = optimize.minimize(self._f, x0 = init_theta,\n# method = self.optimization_method, jac = True,\n# options = self.method_specific_options)\n self.result = pso_adv.PSO(self._f, le, self.init_theta, \n self.p_size, lambda x: all(x<3) and all(x>-3), self.vmax,\n self.w, self.c1 , self.c2, self.maxiter,\n nor_perceptron = 10, nor_r = 0.2).get_ans()\n\n self.optimized_theta = []\n optimized_theta = self.result[0]\n theta_idx = 0\n for i in range(self.L - 1):\n theta_shape = (self.layers[i] + 1, self.layers[i + 1])\n theta_len = theta_shape[0] * theta_shape[1]\n self.optimized_theta.append(\n optimized_theta[theta_idx : theta_idx + theta_len]\n .reshape(theta_shape))\n theta_idx += theta_len\n\n def predict(self, X):\n labels_idx = self.predict_proba(X).argmax(axis = 1)\n return map(lambda x: self.labels_index_map[x], labels_idx)\n\n def predict_proba(self, X):\n self.A[0] = X\n m = X.shape[0]\n\n for i in range(self.L - 1):\n _X = np.hstack((np.ones((m, 1)), self.A[i]))\n self.A[i + 1] = self._sigma(_X.dot(self.optimized_theta[i]))\n\n return self.A[-1]\n\n","sub_path":"ANN_model/pso_ann.py","file_name":"pso_ann.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616144551","text":"# Adventure 8: banana.py\n#\n# From the book: \"Adventures in Minecraft\", 2nd Edition\n# written by David Whale and Martin O'Hanlon, Wiley, 2017\n# http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1119439582.html\n#\n# This program senses when you touch a banana connected to your micro:bit\n\nimport microbit\nimport time\n\nBANANA = microbit.Image(\"00090:00090:00990:09900:99000\")\n\nwhile True:\n time.sleep(0.25)\n if microbit.pin0.is_touched():\n microbit.display.show(BANANA)\n else:\n microbit.display.show('?')\n\n# END\n\n","sub_path":"Adventure8/banana.py","file_name":"banana.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"146266018","text":"from . import actionTable\nimport depot\nfrom . import experiment\nimport gui\nimport util\n\nimport decimal\nimport math\nimport wx\n\n## Provided so the UI knows what to call this experiment.\nEXPERIMENT_NAME = 'RotatorSweep'\n\n\n## This class handles classic Z-stack experiments.\nclass RotatorSweepExperiment(experiment.Experiment):\n def __init__(self, polarizerHandler=None, settlingTime=0.1,\n startV=0.0, maxV=10., vSteps=100, *args, **kwargs):\n experiment.Experiment.__init__(self, *args, **kwargs)\n self.polarizerHandler = polarizerHandler\n self.settlingTime = settlingTime\n # Look up the rotator analogue line handler.\n self.lineHandler = polarizerHandler.getLineHandler()\n self.vRange = (startV, maxV, vSteps)\n vDelta = float(maxV - startV) / vSteps\n # Add voltage parameters to the metadata.\n self.metadata = 'Rotator start and delta: [%f, %f]' % (startV, vDelta)\n\n\n ## Create the ActionTable needed to run the experiment.\n def generateActions(self):\n table = actionTable.ActionTable()\n curTime = 0\n vStart, vLessThan, vSteps = self.vRange\n dv = float(vLessThan - vStart) / float(vSteps)\n dt = decimal.Decimal(self.settlingTime)\n\n for step in range(vSteps):\n # Move to next polarization rotator voltage.\n vTarget = vStart + step * dv\n table.addAction(curTime, self.lineHandler, vTarget)\n curTime += dt\n # Image the sample.\n for cameras, lightTimePairs in self.exposureSettings:\n curTime = self.expose(curTime, cameras, lightTimePairs, table)\n # Advance the time very slightly so that all exposures\n # are strictly ordered.\n curTime += decimal.Decimal('.001')\n # Hold the rotator angle constant during the exposure.\n table.addAction(curTime, self.lineHandler, vTarget)\n # Advance time slightly so all actions are sorted (e.g. we\n # don't try to change angle and phase in the same timestep).\n curTime += dt\n\n return table\n\n\n## A consistent name to use to refer to the class itself.\nEXPERIMENT_CLASS = RotatorSweepExperiment\n\n\n## Generate the UI for special parameters used by this experiment.\nclass ExperimentUI(wx.Panel):\n def __init__(self, parent, configKey):\n wx.Panel.__init__(self, parent = parent)\n self.configKey = configKey\n sizer = wx.GridSizer(2, 4, 1)\n ## Maps strings to TextCtrls describing how to configure\n # response curve experiments.\n self.settings = self.loadSettings()\n self.settlingTimeControl = gui.guiUtils.addLabeledInput(\n self, sizer, label='settling time',\n defaultValue=self.settings['settlingTime'],)\n sizer.Add(self.settlingTimeControl)\n self.vStepsControl = gui.guiUtils.addLabeledInput(\n self, sizer, label='V steps',\n defaultValue=self.settings['vSteps'],)\n sizer.Add(self.vStepsControl)\n self.startVControl = gui.guiUtils.addLabeledInput(\n self, sizer, label='V start',\n defaultValue=self.settings['startV'],)\n sizer.Add(self.startVControl)\n self.maxVControl = gui.guiUtils.addLabeledInput(\n self, sizer, label='V max',\n defaultValue=self.settings['maxV'],)\n sizer.Add(self.maxVControl)\n self.SetSizerAndFit(sizer)\n\n\n ## Given a parameters dict (parameter name to value) to hand to the\n # experiment instance, augment them with our special parameters.\n def augmentParams(self, params):\n self.saveSettings()\n params['settlingTime'] = gui.guiUtils.tryParseNum(self.settlingTimeControl, float)\n params['startV'] = gui.guiUtils.tryParseNum(self.startVControl, float)\n params['maxV'] = gui.guiUtils.tryParseNum(self.maxVControl, float)\n params['vSteps'] = gui.guiUtils.tryParseNum(self.vStepsControl)\n params['polarizerHandler'] = depot.getHandlerWithName('SI polarizer')\n return params\n\n\n ## Load the saved experiment settings, if any.\n def loadSettings(self):\n return util.userConfig.getValue(\n self.configKey + 'RotatorSweepExperimentSettings',\n default = {\n 'settlingTime': '0.1',\n 'startV' : '0.0',\n 'maxV': '10.0',\n 'vSteps': '100',\n }\n )\n\n\n ## Generate a dict of our settings.\n def getSettingsDict(self):\n return {\n 'settlingTime': self.settlingTimeControl.GetValue(),\n 'startV': self.startVControl.GetValue(),\n 'maxV': self.maxVControl.GetValue(),\n 'vSteps': self.vStepsControl.GetValue(),}\n\n\n ## Save the current experiment settings to config.\n def saveSettings(self, settings = None):\n if settings is None:\n settings = self.getSettingsDict()\n util.userConfig.setValue(\n self.configKey + 'RotatorSweepExperimentSettings',\n settings)\n","sub_path":"experiment/rotatorSweep.py","file_name":"rotatorSweep.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"129948540","text":"# ccle_pre_mut.py\r\n# Prepare easy to read mutation file: ccle_pat2mut.txt, ccle_setmut.txt\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# process data part.\r\nidx2mut = {}\r\nf = open('rawdata/CCLE_MUT.csv','r')\r\nfor line in f:\r\n line = line.strip().split(',')\r\n idx2mut = {idx:mut[1:-1].lower() for idx,mut in enumerate(line[1:])}\r\n break\r\n\r\nf1 = open('inputdata/ccle_pat2mut.txt','w')\r\nfor line in f:\r\n line = line.strip().split(',')\r\n can = line[0][1:-1].lower()\r\n Idx = np.where(np.asarray(line[1:],dtype=int)==1)[0]\r\n Mut = [idx2mut[idx] for idx in Idx]\r\n # note: 106 cell lines do not have any mutation information: \r\n # ignore them.\r\n if len(Mut) == 0: continue\r\n print >> f1, can+'\\t'+'\\t'.join(Mut)\r\nf1.close()\r\nf.close()\r\n# stat: 937 pat\r\n\r\n\r\nsetmut = set()\r\nnummut = []\r\nf = open('inputdata/ccle_pat2mut.txt','r')\r\nfor line in f:\r\n line = line.strip().split('\\t')\r\n setmut = setmut | set(line[1:])\r\n nummut.append(len(line[1:]))\r\nsetmut = sorted(list(setmut))\r\nprint >> open('inputdata/ccle_setmut.txt','w'), '\\n'.join(setmut)\r\n# stat: 1639 mut\r\n\r\nplt.plot(nummut,'k.')\r\n# stat: mean=68.3, media=49\r\n\r\n#EOF.","sub_path":"charge/ccle/ccle_pre_mut.py","file_name":"ccle_pre_mut.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"251667361","text":"# https://youtu.be/6Ilb270zYpU\n# https://repl.it/student/assignments/499618/model_solution?fromSubmissionId=1891345\n\n\"\"\"Define a class with the `class` keyword\"\"\"\nclass Node:\n \"\"\"The `__init__` method on a class in Python is analogous\n with JavaScript's `constructor` method; it specifies how a\n class should be initialized give some parameters. You'll\n also notice the `self` keyword, which is passed in to\n every class method as the first argument. It's very much\n analogous to JavaScript's `this` keyword.\"\"\"\n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next_node = next_node\n\n \"\"\"Returns the data stored at the current node\"\"\"\n def get_data(self):\n return self.data\n\n \"\"\"Returns the next node this node points to\"\"\"\n def get_next(self):\n return self.next_node\n\n \"\"\"Sets this node's `next_node` pointer\"\"\"\n def set_next(self, new_next):\n self.next_node = new_next\n\n\n\"\"\"Now that we've defined our `Node`, we can define our Linked List\nclass, which will utilize our `Node` class\"\"\"\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n \"\"\"Wraps the input item in a Node and adds it as the\n current node's next node\"\"\"\n def insert(self, item):\n new_node = Node(item)\n new_node.set_next(self.head)\n self.head = new_node\n\n \"\"\"Returns the number of nodes in the linked list\"\"\"\n def size(self):\n current = self.head\n count = 0\n while current:\n count += 1\n current = current.get_next()\n return count\n\n \"\"\"Returns the target item if it is in the linked list,\n and None otherwise\"\"\"\n def search(self, target):\n current = self.head\n found = False\n while current and found is False:\n if current.get_data() == target:\n found = True\n else:\n current = current.get_next()\n return current\n\n \"\"\"Deletes the target item from the linked list if it is\n in the list. Raises a ValueError exception otherwise if\n the target item is not in the list\"\"\"\n def delete(self, target):\n current = self.head\n previous = None\n found = False\n while current and found is False:\n if current.get_data() == target:\n found = True\n else:\n previous = current\n current = current.get_next()\n if current is None:\n raise ValueError('Data not in list')\n if previous is None:\n self.head = current.get_next()\n else:\n previous.set_next(current.get_next())\n \n","sub_path":"cc73linkedList/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"112419111","text":"import pygame\n\nWIDTH = 1000\nHEIGHT = int(WIDTH * 2 / 3)\n\ndef render(surface, n: dict):\n for key, value in n.items():\n surface.blit(value, key)\n\n return surface\n\n\nclass BackgroundChanger:\n\n def __init__(self):\n self.background_id = 0\n\n def background(self, id:int = None):\n if id != self.background_id:\n self.background_id = id\n background = pygame.image.load(f\"./assets/backgrounds/background_{self.background_id}.jpg\")\n background = pygame.transform.scale(background, (WIDTH, HEIGHT))\n return background\n","sub_path":"include/renderer.py","file_name":"renderer.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"68464267","text":"import asyncio\nimport uuid \nfrom zipfile import ZipFile\nfrom os import listdir, path\nfrom json import loads, dumps\nfrom datetime import datetime\n\nfrom ..db import conn\nfrom ..servernet import get_server_file\n\nasync def store_stats_in_database():\n\tcursor = conn.cursor()\n\tprint(\"Preparing to update player stats...\")\n\tbackups_folder = get_server_file()\n\n\tall_zips = [f for f in listdir(backups_folder) if f.endswith('.zip')]\n\tall_zips = sorted(all_zips)\n\t\n\t# Store the final data to be stored in DB\n\tdata_by_date: dict = {}\n\tfor fname in all_zips:\n\t\t# Grab fnames that have actual backup data\n\t\tprint(f\"Processing {fname} for stats\")\n\t\ttry:\n\t\t\t# The date to associate this particular data point with\n\t\t\t# The file is of the format Backup--world--DATE\n\t\t\t# So just ignore irrelevant strings including zip extension\n\t\t\traw_date = fname[:-4]\n\t\t\tparsed_date = datetime.strptime(raw_date, \"%Y-%m-%d-%H-%M-%S\")\n\n\t\t\twith ZipFile(path.join(backups_folder, fname), 'r') as zf:\n\t\t\t\tuser_datas = []\n\t\t\t\t# Could potentially break if some other stats folder comes into play.\n\t\t\t\tstats_fnames = [f for f in zf.namelist() if f.startswith(f\"world{path.sep}stats{path.sep}\") and f.endswith(\".json\")]\n\n\t\t\t\tfor stat_fname in stats_fnames:\n\t\t\t\t\t# Get the UUID of the user by parsing file name\n\t\t\t\t\t# Separate by folder delimitter and then remove json extension\n\t\t\t\t\tuniq_id = stat_fname.split(path.sep)[-1][:-5]\n\n\t\t\t\t\tf = zf.read(stat_fname)\n\t\t\t\t\t\n\t\t\t\t\t# Process the loaded data\n\t\t\t\t\tparsed_data = (str(uuid.uuid4()), parsed_date.strftime('%Y-%m-%dT%H:%M:%S.000Z'), uniq_id, f)\n\t\t\t\t\tuser_datas.append(parsed_data)\n\n\t\t\t\tcursor.executemany(\"INSERT OR IGNORE INTO PlayerStats (id, date, userId, stats) VALUES (?, ?, ?, ?)\", user_datas)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\n\tconn.commit()\n\tprint(\"Done updating player stats\")\n\t\t\t\t\t\t\t\t\t\ndef clean_stats_json(loaded_json: dict) -> dict:\n\t\"\"\"JSON loads makes each element in the stats file\n\tinto its own key, and doesn't recursively create\n\ta dict. Fix that by doing exactly that.\"\"\"\n\tcleaned_json = {}\n\n\tfor key, value in loaded_json.items():\n\t\t# We need the last element too because some stats\n\t\t# hold accumulations of all its children.\n\t\tpath_list = key.split(\".\")\n\n\t\tdrill = cleaned_json\n\t\tfor stat_key in path_list:\n\t\t\tdrill = drill.setdefault(stat_key, {})\n\n\t\t# To remove ambiguity and type checking, store the\n\t\t# actual stat value in a unique key.\n\t\tdrill[\"_stat\"] = value\t\n\n\treturn cleaned_json","sub_path":"mcdiscord/schedule/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"81180591","text":"import re\nfrom typing import Callable, List\n\nfrom langdetect import detect_langs\nfrom nltk import word_tokenize, WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\nfrom voikko_lemmatizer import VoikkoLemmatizer\n\nSTOPWORDS = stopwords.words('english') + stopwords.words('finnish')\n\n\ndef tokenize_and_clean_text(text: str,\n tokenization_method: Callable,\n lemmatization_method: Callable = None,\n strip_character_list: List[str] = None,\n stopwords: List[str] = None):\n text = text.lower()\n if strip_character_list:\n text = remove_characters(text, strip_character_list)\n\n tokens = tokenization_method(text)\n if stopwords:\n tokens = remove_stopwods(stopwords, tokens)\n\n if lemmatization_method:\n tokens = lemmatization_method(tokens)\n\n tokens = remove_non_alphabetic_characters(tokens)\n return tokens\n\n\ndef remove_non_alphabetic_characters(tokens):\n tokens = [token for token in tokens if token.isalpha()]\n return tokens\n\n\ndef remove_stopwods(stopwords, tokens):\n tokens = [token for token in tokens if token not in stopwords]\n return tokens\n\n\ndef lemmatize_english_tokens(tokens):\n lemmatization_method = WordNetLemmatizer().lemmatize\n lemmas = [lemmatization_method(token) for token in tokens]\n return lemmas\n\n\ndef lemmatize_finnish_tokens(tokens):\n return VoikkoLemmatizer().lemmatize(tokens)\n\n\ndef remove_characters(text, characters):\n for c in characters:\n text = text.replace(c, '')\n return text\n\n\ndef tokenize_and_clean_finnish_text(text: str):\n tokenization_method = re.compile(r'\\S+').findall\n strip_character_list = ['.', ',', '-']\n lemmatization_method = lemmatize_finnish_tokens\n tokens = tokenize_and_clean_text(text,\n tokenization_method=tokenization_method,\n strip_character_list=strip_character_list,\n stopwords=STOPWORDS,\n lemmatization_method=lemmatization_method)\n return tokens\n\n\ndef tokenize_and_clean_english_text(text: str):\n tokenization_method = word_tokenize\n strip_character_list = ['.', ',', '-']\n lemmatization_method = lemmatize_english_tokens\n tokens = tokenize_and_clean_text(text,\n tokenization_method=tokenization_method,\n strip_character_list=strip_character_list,\n stopwords=STOPWORDS,\n lemmatization_method=lemmatization_method)\n return tokens\n\n\ndef detect_language(text):\n results = detect_langs(text)\n results_dict = [result.__dict__ for result in results]\n language = results_dict[0].get('lang', None)\n probability = results_dict[0].get('prob', None)\n return language, probability\n\n\ndef process_text(text: str):\n language, probability = detect_language(text)\n processing_methods_by_language = {\n 'en': tokenize_and_clean_english_text,\n 'fi': tokenize_and_clean_finnish_text,\n }\n processing_method = processing_methods_by_language.get(language, re.compile(r'\\S+').findall)\n tokens = processing_method(text)\n return tokens\n\n\ndef process_documents(documents: List[str]):\n return [process_text(document) for document in documents]\n","sub_path":"text_processing.py","file_name":"text_processing.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"480694044","text":"import sys\nimport os\nfrom argparse import ArgumentParser\n\nimport requests\nimport arrow\n\nURL = 'http://localhost:7000'\n\ndef main():\n # create new data collection in Uploads collection\n upload_collection = requests.get(os.path.join(URL, 'api/services/datacollection/get_upload_collection')).json()\n upload_collection_guid = upload_collection['guid']\n\n # create new data collection for upload data\n current_date = arrow.utcnow().format('YYYY-MM-DD_HH:mm:ss')\n\n data = {\n 'name': 'upload {}'.format(current_date),\n 'parentguid': upload_collection_guid\n }\n\n new_databucketcollection = requests.post(os.path.join(URL, 'api/rasterdatabucketcollection/'), json=data).json()\n new_databucketcollection_guid = new_databucketcollection['guid']\n\n # create new databucket for upload data\n data = {\n 'name': 'new_upload',\n 'collectionguid': new_databucketcollection_guid\n }\n\n new_databucket = requests.post(os.path.join(URL, 'api/rasterdatabucket/'), json=data).json()\n\n target_bucketid = new_databucket['guid']\n\n # upload data into new databucket\n print('target bucket: {}'.format(target_bucketid))\n upload_file = '../tiles/server/data/strm/input/s22_e026_1arc_v3.zip'\n\n payload = {\n 'bucketid': target_bucketid\n }\n\n files = {\n 'file': open(upload_file, 'rb')\n }\n upload_url = 'http://localhost:7000/api/rasterdatabucket/{}/upload'.format(target_bucketid)\n upload = requests.post(upload_url, data=payload, files=files)\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"archive/webclient-databucket-system/tools/load_srtm_data.py","file_name":"load_srtm_data.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"504137688","text":"from os import close\nimport sqlite3\nfrom tkinter import messagebox as mb\n\nclass Pokemons:\n\n\t# Aqui es donde se administra toda la informacion en la base de datos\n\t# usando estos metodos.\n\t# se crea un atributo llamado lugar para poder interar en \n\t# las filas de la base de datos, mas abajo se va a explicar en detalles.\n\t# En caso de que la base de datos no exista se va a crear junto a su tabla.\n\tdef __init__(self):\n\t\tself.lugar = -1\n\t\ttry:\n\t\t\tconexion = sqlite3.connect(\"Pokemones.db\")\n\t\t\tcursor = conexion.cursor()\n\t\t\tsql = \"\"\"create table pokemones (\n\t\t\t\t\t\tnumero integer primary key,\n\t\t\t\t\t\tpokemon text,\n\t\t\t\t\t\tnombre text,\n\t\t\t\t\t\taltura real,\n\t\t\t\t\t\tpeso real,\n\t\t\t\t\t\ttipos text,\n\t\t\t\t\t\tcomida text,\n\t\t\t\t\t\timagenPath text,\n\t\t\t\t\t\tdescripcion text\n\t\t\t\t\t)\"\"\"\n\t\t\tcursor.execute(sql)\n\t\texcept sqlite3.OperationalError:\n\t\t\tpass\n\t\n\t# Abre la conexion con la base de datos\n\tdef abrir(self):\n\t\tconexion = sqlite3.connect(\"Pokemones.db\")\n\t\treturn conexion\n\t\n\t# Aqui es donde se administra la informacion mandada por el metodo\n\t# guardar de modulo Formulario, esta es insertada ala base de datos apenas\n\t# es recibida.\n\tdef subir(self,datos):\n\t\ttry:\n\t\t\tcone = self.abrir()\n\t\t\tcursor = cone.cursor()\n\t\t\tsql = \"\"\"insert into pokemones(\n\t\t\t\t\t\tnumero,\n\t\t\t\t\t\tpokemon,\n\t\t\t\t\t\tnombre,\n\t\t\t\t\t\taltura,\n\t\t\t\t\t\tpeso,\n\t\t\t\t\t\ttipos,\n\t\t\t\t\t\tcomida,\n\t\t\t\t\t\timagenPath,\n\t\t\t\t\t\tdescripcion\n\t\t\t\t\t) values (?,?,?,?,?,?,?,?,?)\"\"\"\n\t\t\tcursor.execute(sql, datos)\n\t\t\treturn cursor.rowcount\n\t\texcept sqlite3.IntegrityError:\n\t\t\tmb.showinfo(\"Error!\", \"Ya existe un pokemon con ese numero de identificacion intenta otro numero\")\n\t\tfinally:\n\t\t\tcone.commit()\n\t\t\tcone.close()\n\n\n\n\t# Iterar es un metodo llamado por el metodo guardar del modulo\n\t# PokedexGUI, ambos metodos reciben un parametro llamado direccion, \n\t# el proposito de este parametro es el de ser sumado al atributo lugar,\n\t# este atributo tiene como proposito ser un idicie ala hora de iterar en\n\t# las filas de la base de datos, debido a que este metodo se construyo de manera\n\t# de que toda la informacion de la base de datos sea recibida en forma de lista,\n\t# siendo asi el atributo lugar en indice de ella que indicia que fila retornar ala \n\t# PokedexGUI para que esta mustre su inforamcion, al summar 1 al atriubuto lugar\n\t# se avanza en las filas de la base de datos y viceversa cuando se suma -1\n\tdef iterar(self, direccion):\n\t\ttry:\n\t\t\tself.lugar += direccion\n\t\t\tcone = self.abrir()\n\t\t\tcursor = cone.cursor()\n\t\t\tsql = \"select * from pokemones\"\n\t\t\tif self.lugar < 0:\n\t\t\t\tmb.showinfo(\"Informacion\", \"Estas en el principio de los registros de la Pokedex, intenta avanzar\")\n\t\t\t\tself.lugar = 0\n\t\t\tcursor.execute(sql)\n\t\t\tinformacion = cursor.fetchall()\n\t\t\treturn informacion[self.lugar]\n\t\texcept IndexError:\n\t\t\tmb.showinfo(\"Informacion\", \"Llegaste al final de la Pokedex, intenta atrapar mas Pokemones!\")\n\t\t\tself.lugar -= 1\n\t\tfinally:\n\t\t\tcone.close()\n\n\tdef editar(self, datos):\n\t\ttry:\n\t\t\tcone = self.abrir()\n\t\t\tcursor = cone.cursor()\n\t\t\tsql = \"\"\"update pokemones set\n\t\t\tpokemon=?, \n\t\t\tnombre=?,\n\t\t\taltura=?,\n\t\t\tpeso=?,\n\t\t\ttipos=?,\n\t\t\tcomida=?,\n\t\t\timagenPath=?,\n\t\t\tdescripcion=? where numero=? \"\"\"\n\t\t\tcursor.execute(sql, datos)\n\t\t\treturn cursor.rowcount\n\t\tfinally:\n\t\t\tcone.commit()\n\t\t\tcone.close()\n\t\n\tdef borrar(self, dato):\n\t\ttry:\n\t\t\tcone = self.abrir()\n\t\t\tcursor = cone.cursor()\n\t\t\tsql = \"delete from pokemones where numero=?\"\n\t\t\tcursor.execute(sql, dato)\n\t\t\treturn cursor.rowcount\n\t\tfinally:\n\t\t\tcone.commit()\n\t\t\tcone.close()\n\n\tdef buscar(self, dato):\n\t\ttry:\n\t\t\tcone = self.abrir()\n\t\t\tcursor = cone.cursor()\n\t\t\tsql = \"\"\"select pokemon, \n\t\t\t\tnombre, \n\t\t\t\taltura,\n\t\t\t\tpeso,\n\t\t\t\ttipos,\n\t\t\t\tcomida,\n\t\t\t\timagenPath,\n\t\t\t\tdescripcion from pokemones where numero=?\"\"\"\n\t\t\tcursor.execute(sql, dato)\n\t\t\treturn cursor.fetchone()\n\t\tfinally:\n\t\t\tcone.close()\n","sub_path":"Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"137741991","text":"from django.template import Library\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom site_core.models import Parameter\nimport json\n\nregister = Library()\n\n\n@register.assignment_tag\ndef html_from_parameters(name):\n try:\n parameter = Parameter.objects.get(name=name)\n if parameter.enable:\n return parameter.value\n else:\n return ''\n except ObjectDoesNotExist:\n return ''\n\n\n","sub_path":"site_core/templatetags/site_core_extras.py","file_name":"site_core_extras.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"214856353","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\nheader = {\n 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'\n}\n\nurl = 'http://jandan.net/ooxx/page-2063'\nfileName = 'D:\\\\Code\\\\Python日常\\\\jiandan_ooxx'\n\ndef download_url(url):\n try:\n request = urllib.request.Request(url,None,header)\n response = urllib.request.urlopen(request)\n content = response.read().decode('UTF-8')\n return content\n except urllib.request.URLError as e:\n print(\"[访问出错]\" + e.reason)\n return None\ndef download_image(imageUrl):\n try:\n print(\"正在下载......\" + str(imageUrl))\n urllib.request.urlretrieve(imageUrl,fileName)\n except urllib.request.URLError as e:\n print(\"[下载出错]\\n\" + e.reason)\n return None\ndef get_url(content):\n soup = BeautifulSoup(content,\"html.parser\")\n contents = soup.find_all('a',attrs={'class':'view_img_link'})\n for i in contents:\n return i.get('href')\nif __name__ == \"__main__\":\n download_image(get_url(download_url(url)))\n\n","sub_path":"Python/jiandan_ooxx.py","file_name":"jiandan_ooxx.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"572099385","text":"from django.db.models.signals import post_save, post_delete\nfrom django.db.utils import OperationalError\nfrom django.dispatch import receiver\nfrom django.contrib.admin.models import LogEntry\n\nfrom apps.hello.models import DBAction\n\n\nIGNORED_SENDERS = (DBAction, LogEntry)\n\n\ndef create_DBAction(sender, action):\n try:\n DBAction.objects.create(\n model=sender.__name__,\n action=action\n )\n except OperationalError:\n pass\n\n\n@receiver(post_save) # noqa\ndef object_created_or_updated(sender, created, **kwargs):\n if sender in IGNORED_SENDERS:\n return\n\n create_DBAction(sender, action=('created' if created else 'updated'))\n\n\n@receiver(post_delete) # noqa\ndef object_deleted(sender, **kwargs):\n if sender in IGNORED_SENDERS:\n return\n\n create_DBAction(sender, 'deleted')\n","sub_path":"apps/hello/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"168698306","text":"from doubly_linked_list import DoublyLinkedList\n\nclass LRUCache:\n \"\"\"\n Our LRUCache class keeps track of the max number of nodes it\n can hold, the current number of nodes it is holding, a doubly-\n linked list that holds the key-value entries in the correct\n order, as well as a storage dict that provides fast access\n to every node stored in the cache.\n \"\"\"\n def __init__(self, limit=10):\n #Plan\n #limits the amt of nodes cache can hold to 10\n #show current number of nodes it has\n #variable used to set the value being set by Doublylinked list, a list that holds the key-value entries\n #dictionary for access (hash table) s well as a storage dict that provides fast access to every node stored in the cache.\n self.limit = limit\n self.size = 0\n self.order = DoublyLinkedList()\n self.storage = {}\n\n \"\"\"\n Retrieves the value associated with the given key. Also\n needs to move the key-value pair to the end of the order\n such that the pair is considered most-recently used.\n Returns the value associated with the key or None if the\n key-value pair doesn't exist in the cache.\n \"\"\"\n def get(self, key):\n # plan if there is a key in storage, move to the front, then refresh the order and return the value which is a truple, else return none\n if key in self.storage:\n node = self.storage[key]\n self.order.move_to_front(node)\n return node.value[1]\n else:\n return None\n\n \n \n\n \"\"\"\n Adds the given key-value pair to the cache. The newly-\n added pair should be considered the most-recently used\n entry in the cache. If the cache is already at max capacity\n before this entry is added, then the oldest entry in the\n cache needs to be removed to make room. Additionally, in the\n case that the key already exists in the cache, we simply\n want to overwrite the old value associated with the key with\n the newly-specified value.\n \"\"\"\n def set(self, key, value):\n if key in self.storage:\n node = self.storage[key]\n node.value = (key, value)\n self.order.move_to_front(node)\n return\n\n if self.size is self.limit:\n del self.storage[self.order.tail.value[0]]\n self.order.remove_from_tail()\n self.size -= 1\n self.order.add_to_head((key, value))\n self.storage[key] = self.order.head\n self.size += 1\n\n ","sub_path":"lru_cache/lru_cache.py","file_name":"lru_cache.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"86990657","text":"\"\"\"This function crosses information of the several channels.\n\nAfter loading the segmented spots and nuclei, it calculates nucleus per nucleus\nthe matrix of the distances between all the spots of the three chennels; we can have\na maximum of 2 dots per channel, and all the six possible distances are calculated\nin order the minimu possible distance for un association, not for the sum of the distances.\nEx: c1, c2, e1, e2 are goi,ng to be associated like c1-e1, c2-e2 if d(c1-e1) (or d(c2-e2)) is\nthe shortest possbile distance, we don't care if at the end\nd(c1-e1) + d(c2-e2) > d(c1-e2) + d(c2-e1)\n\"\"\"\n\nimport numpy as np\nfrom skimage.measure import label, regionprops_table\nimport xlsxwriter\n# import pyqtgraph as pg\nfrom PyQt5 import QtWidgets\n\n\ndef dist_choose(x1, x2, pix_sizeZ, pix_sizeX):\n \"\"\"Calculates the distances between to 3D points: if one is (0,0,0), gives 1000000000\"\"\"\n if x1.sum() == 0 or x2.sum() == 0:\n dist = 1000000000\n else:\n dist = np.sqrt(((x1[0] - x2[0]) * pix_sizeZ) ** 2 + ((x1[1] - x2[1]) * pix_sizeX) ** 2 + ((x1[2] - x2[2]) * pix_sizeX) ** 2)\n return dist\n\n\nclass CrossInfo:\n \"\"\"Only class, does all the job\"\"\"\n def __init__(self, analysis_folder, spts_chs_modif):\n\n spts_ch1 = spts_chs_modif[:, :, :, 0] # load analysis results\n spts_ch2 = spts_chs_modif[:, :, :, 1]\n spts_ch3 = spts_chs_modif[:, :, :, 2]\n nucs_dapi = np.load(analysis_folder + '/nucs_dapi.npy')\n pix_sizeZ, pix_sizeX = np.load(analysis_folder + '/pix_sizes.npy')\n try:\n spts_clusters_flag = np.load(analysis_folder + '/spts_clstrs_flag.npy')\n except FileNotFoundError:\n spts_clusters_flag = 1\n\n spts_ch1_lbls = label(spts_ch1, connectivity=1) # spots labeling\n spts_ch2_lbls = label(spts_ch2, connectivity=1)\n spts_ch3_lbls = label(spts_ch3, connectivity=1)\n\n rgp_ch1 = regionprops_table(spts_ch1_lbls, properties=[\"label\", \"coords\", \"area\"]) # dictionary with useful info of spots\n rgp_ch2 = regionprops_table(spts_ch2_lbls, properties=[\"label\", \"coords\", \"area\"])\n rgp_ch3 = regionprops_table(spts_ch3_lbls, properties=[\"label\", \"coords\", \"area\"])\n\n idxs2rm_ch1 = np.where(rgp_ch1[\"area\"] < 4)[0] # check id of spots smaller than 4 pixels to delete them\n idxs2rm_ch2 = np.where(rgp_ch2[\"area\"] < 4)[0]\n idxs2rm_ch3 = np.where(rgp_ch3[\"area\"] < 4)[0]\n\n for kk in idxs2rm_ch1:\n spts_ch1[rgp_ch1[\"coords\"][kk][:, 0], rgp_ch1[\"coords\"][kk][:, 1], rgp_ch1[\"coords\"][kk][:, 2]] = 0 # remove small spots using the coordinates of the pixels of the spots itself\n\n for kk in idxs2rm_ch2:\n spts_ch2[rgp_ch2[\"coords\"][kk][:, 0], rgp_ch2[\"coords\"][kk][:, 1], rgp_ch2[\"coords\"][kk][:, 2]] = 0\n\n for kk in idxs2rm_ch3:\n spts_ch3[rgp_ch3[\"coords\"][kk][:, 0], rgp_ch3[\"coords\"][kk][:, 1], rgp_ch3[\"coords\"][kk][:, 2]] = 0\n\n spts_ch1_lbls = label(spts_ch1, connectivity=1) # relabel spots after removal of small objects\n spts_ch2_lbls = label(spts_ch2, connectivity=1)\n spts_ch3_lbls = label(spts_ch3, connectivity=1)\n\n rgp_ch1 = regionprops_table(spts_ch1_lbls, properties=[\"label\", \"centroid\", \"area\", \"coords\"]) # new dictionary of the selected spots\n rgp_ch2 = regionprops_table(spts_ch2_lbls, properties=[\"label\", \"centroid\", \"area\", \"coords\"])\n rgp_ch3 = regionprops_table(spts_ch3_lbls, properties=[\"label\", \"centroid\", \"area\", \"coords\"])\n\n idxs_nucs = np.unique(nucs_dapi)[1:] # tags of the nuclei\n dists_mtx = np.zeros((6, idxs_nucs.size)) # matrix of the distances: for each nucleus you have at maximum 6 distances (c1-e1, c2-e2, c1-s1, c2-s2, e1-, s1, e2-s2)\n\n spts_ch1_fin = np.zeros(spts_ch1.shape, np.uint8)\n spts_ch2_fin = np.zeros(spts_ch2.shape, np.uint8)\n spts_ch3_fin = np.zeros(spts_ch3.shape, np.uint8)\n\n pbar = ProgressBar(total1=idxs_nucs.size)\n pbar.show()\n pbar.update_progressbar1(0)\n\n # print(counts)\n for counts, jj in enumerate(idxs_nucs):\n pbar.update_progressbar1(counts)\n sing_nuc = (nucs_dapi == jj) # for each nucleus\n # CH1\n spts_ch1_sing_tags = spts_ch1_lbls * sing_nuc # find the tag of the ch1 spots inside the single nucleus\n spts_ch1_sing_tags = spts_ch1_sing_tags[spts_ch1_sing_tags != 0]\n spts_ch1_sing_tags = np.unique(spts_ch1_sing_tags)\n spts_ch1_sing_idxs = list()\n for gg in spts_ch1_sing_tags:\n spts_ch1_sing_idxs.append(np.where(rgp_ch1[\"label\"] == gg)[0][0])\n\n ctrs_ch1 = np.zeros((2, 3))\n\n if len(spts_ch1_sing_idxs) >= 2:\n area_idxs = np.zeros((2, len(spts_ch1_sing_idxs)))\n area_idxs[0, :] = np.take(rgp_ch1[\"area\"], spts_ch1_sing_idxs)\n area_idxs[1, :] = np.asarray(spts_ch1_sing_idxs)\n area_idxs = (area_idxs[:, area_idxs[0].argsort()][1, -2:]).astype(np.int64)\n ctrs_ch1[0, :] = np.array([rgp_ch1[\"centroid-0\"][area_idxs[0]], rgp_ch1[\"centroid-1\"][area_idxs[0]], rgp_ch1[\"centroid-2\"][area_idxs[0]]])\n ctrs_ch1[1, :] = np.array([rgp_ch1[\"centroid-0\"][area_idxs[1]], rgp_ch1[\"centroid-1\"][area_idxs[1]], rgp_ch1[\"centroid-2\"][area_idxs[1]]])\n spts_ch1_fin[rgp_ch1[\"coords\"][area_idxs[0]][:, 0], rgp_ch1[\"coords\"][area_idxs[0]][:, 1], rgp_ch1[\"coords\"][area_idxs[0]][:, 2]] = 1\n spts_ch1_fin[rgp_ch1[\"coords\"][area_idxs[1]][:, 0], rgp_ch1[\"coords\"][area_idxs[1]][:, 1], rgp_ch1[\"coords\"][area_idxs[1]][:, 2]] = 1\n\n if len(spts_ch1_sing_idxs) == 1:\n ctrs_ch1[0, :] = np.array([rgp_ch1[\"centroid-0\"][spts_ch1_sing_idxs[0]], rgp_ch1[\"centroid-1\"][spts_ch1_sing_idxs[0]], rgp_ch1[\"centroid-2\"][spts_ch1_sing_idxs[0]]])\n spts_ch1_fin[rgp_ch1[\"coords\"][spts_ch1_sing_idxs[0]][:, 0], rgp_ch1[\"coords\"][spts_ch1_sing_idxs[0]][:, 1], rgp_ch1[\"coords\"][spts_ch1_sing_idxs[0]][:, 2]] = 1\n\n # CH2\n spts_ch2_sing_tags = spts_ch2_lbls * sing_nuc # find the tag of the ch1 spots inside the single nucleus\n spts_ch2_sing_tags = spts_ch2_sing_tags[spts_ch2_sing_tags != 0]\n spts_ch2_sing_tags = np.unique(spts_ch2_sing_tags)\n spts_ch2_sing_idxs = list()\n for gg in spts_ch2_sing_tags:\n spts_ch2_sing_idxs.append(np.where(rgp_ch2[\"label\"] == gg)[0][0])\n\n ctrs_ch2 = np.zeros((2, 3))\n\n if len(spts_ch2_sing_idxs) >= 2:\n area_idxs = np.zeros((2, len(spts_ch2_sing_idxs)))\n area_idxs[0, :] = np.take(rgp_ch2[\"area\"], spts_ch2_sing_idxs)\n area_idxs[1, :] = np.asarray(spts_ch2_sing_idxs)\n area_idxs = (area_idxs[:, area_idxs[0].argsort()][1, -2:]).astype(np.int64)\n ctrs_ch2[0, :] = np.array([rgp_ch2[\"centroid-0\"][area_idxs[0]], rgp_ch2[\"centroid-1\"][area_idxs[0]], rgp_ch2[\"centroid-2\"][area_idxs[0]]])\n ctrs_ch2[1, :] = np.array([rgp_ch2[\"centroid-0\"][area_idxs[1]], rgp_ch2[\"centroid-1\"][area_idxs[1]], rgp_ch2[\"centroid-2\"][area_idxs[1]]])\n spts_ch2_fin[rgp_ch2[\"coords\"][area_idxs[0]][:, 0], rgp_ch2[\"coords\"][area_idxs[0]][:, 1], rgp_ch2[\"coords\"][area_idxs[0]][:, 2]] = 1\n spts_ch2_fin[rgp_ch2[\"coords\"][area_idxs[1]][:, 0], rgp_ch2[\"coords\"][area_idxs[1]][:, 1], rgp_ch2[\"coords\"][area_idxs[1]][:, 2]] = 1\n\n if len(spts_ch2_sing_idxs) == 1:\n ctrs_ch2[0, :] = np.array([rgp_ch2[\"centroid-0\"][spts_ch2_sing_idxs[0]], rgp_ch2[\"centroid-1\"][spts_ch2_sing_idxs[0]], rgp_ch2[\"centroid-2\"][spts_ch2_sing_idxs[0]]])\n spts_ch2_fin[rgp_ch2[\"coords\"][spts_ch2_sing_idxs[0]][:, 0], rgp_ch2[\"coords\"][spts_ch2_sing_idxs[0]][:, 1], rgp_ch2[\"coords\"][spts_ch2_sing_idxs[0]][:, 2]] = 1\n\n # CH3\n spts_ch3_sing_tags = spts_ch3_lbls * sing_nuc # find the tag of the ch1 spots inside the single nucleus: mask the nucleus on the labeled spots\n spts_ch3_sing_tags = spts_ch3_sing_tags[spts_ch3_sing_tags != 0]\n spts_ch3_sing_tags = np.unique(spts_ch3_sing_tags) # find the surviving tags\n spts_ch3_sing_idxs = list()\n for gg in spts_ch3_sing_tags:\n spts_ch3_sing_idxs.append(np.where(rgp_ch3[\"label\"] == gg)[0][0]) # find the indexes in the dictionary of the surviving tags\n\n ctrs_ch3 = np.zeros((2, 3)) # initialize the matrix of centroids\n\n if len(spts_ch3_sing_idxs) >= 2: # if we have 2 spots or more in the mask, search the biggest 2 (it's redundant in case of only 2 spots, but works anyway reducing code complexity)\n area_idxs = np.zeros((2, len(spts_ch3_sing_idxs))) # initialize with volume and relative indexes\n area_idxs[0, :] = np.take(rgp_ch3[\"area\"], spts_ch3_sing_idxs)\n area_idxs[1, :] = np.asarray(spts_ch3_sing_idxs)\n area_idxs = (area_idxs[:, area_idxs[0].argsort()][1, -2:]).astype(np.int64) # sort the matrix with respect to the volume\n ctrs_ch3[0, :] = np.array([rgp_ch3[\"centroid-0\"][area_idxs[0]], rgp_ch3[\"centroid-1\"][area_idxs[0]], rgp_ch3[\"centroid-2\"][area_idxs[0]]]) # record the coordinates of the centroids of the biggest 2\n ctrs_ch3[1, :] = np.array([rgp_ch3[\"centroid-0\"][area_idxs[1]], rgp_ch3[\"centroid-1\"][area_idxs[1]], rgp_ch3[\"centroid-2\"][area_idxs[1]]])\n spts_ch3_fin[rgp_ch3[\"coords\"][area_idxs[0]][:, 0], rgp_ch3[\"coords\"][area_idxs[0]][:, 1], rgp_ch3[\"coords\"][area_idxs[0]][:, 2]] = 1\n spts_ch3_fin[rgp_ch3[\"coords\"][area_idxs[1]][:, 0], rgp_ch3[\"coords\"][area_idxs[1]][:, 1], rgp_ch3[\"coords\"][area_idxs[1]][:, 2]] = 1\n\n if len(spts_ch3_sing_idxs) == 1: # if there is only 1 spot, no sorting is needed\n ctrs_ch3[0, :] = np.array([rgp_ch3[\"centroid-0\"][spts_ch3_sing_idxs[0]], rgp_ch3[\"centroid-1\"][spts_ch3_sing_idxs[0]], rgp_ch3[\"centroid-2\"][spts_ch3_sing_idxs[0]]])\n spts_ch3_fin[rgp_ch3[\"coords\"][spts_ch3_sing_idxs[0]][:, 0], rgp_ch3[\"coords\"][spts_ch3_sing_idxs[0]][:, 1], rgp_ch3[\"coords\"][spts_ch3_sing_idxs[0]][:, 2]] = 1\n\n # FILLING DISTANCE MATRIX\n\n all_d_ce = [dist_choose(ctrs_ch1[0, :], ctrs_ch2[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[0, :], ctrs_ch2[1, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[1, :], ctrs_ch2[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[1, :], ctrs_ch2[1, :], pix_sizeZ, pix_sizeX)]\n\n if np.argmin(all_d_ce) == 1 or np.argmin(all_d_ce) == 2:\n dists_mtx[:2, counts] = all_d_ce[1], all_d_ce[2]\n else:\n dists_mtx[:2, counts] = all_d_ce[0], all_d_ce[3]\n\n all_d_cs = [dist_choose(ctrs_ch1[0, :], ctrs_ch3[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[0, :], ctrs_ch3[1, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[1, :], ctrs_ch3[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch1[1, :], ctrs_ch3[1, :], pix_sizeZ, pix_sizeX)]\n\n if np.argmin(all_d_cs) == 1 or np.argmin(all_d_cs) == 2:\n dists_mtx[2:4, counts] = all_d_cs[1], all_d_cs[2]\n else:\n dists_mtx[2:4, counts] = all_d_cs[0], all_d_cs[3]\n\n all_d_es = [dist_choose(ctrs_ch2[0, :], ctrs_ch3[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch2[0, :], ctrs_ch3[1, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch2[1, :], ctrs_ch3[0, :], pix_sizeZ, pix_sizeX), dist_choose(ctrs_ch2[1, :], ctrs_ch3[1, :], pix_sizeZ, pix_sizeX)]\n\n if np.argmin(all_d_es) == 1 or np.argmin(all_d_es) == 2:\n dists_mtx[4:, counts] = all_d_es[1], all_d_es[2]\n else:\n dists_mtx[4:, counts] = all_d_es[0], all_d_es[3]\n\n pbar.close()\n\n workbook = xlsxwriter.Workbook(analysis_folder + \"/distances_modified.xlsx\")\n sheet1 = workbook.add_worksheet(\"\")\n\n sheet1.write(0, 0, \"Nucs Id\")\n sheet1.write(0, 1, \"Dist ch1_1-ch2_1\")\n sheet1.write(0, 2, \"Dist ch1_2-ch2_2\")\n sheet1.write(0, 3, \"Dist ch1_1-ch3_1\")\n sheet1.write(0, 4, \"Dist ch1_2-ch3_2\")\n sheet1.write(0, 5, \"Dist ch2_1-ch3_1\")\n sheet1.write(0, 6, \"Dist ch2_2-ch3_2\")\n\n for ll in range(dists_mtx.shape[1]):\n sheet1.write(ll + 1, 0, idxs_nucs[ll])\n if dists_mtx[0, ll] < 1000000000:\n sheet1.write(ll + 1, 1, dists_mtx[0, ll])\n else:\n sheet1.write(ll + 1, 1, \"----\")\n\n if dists_mtx[1, ll] < 1000000000:\n sheet1.write(ll + 1, 2, dists_mtx[1, ll])\n else:\n sheet1.write(ll + 1, 2, \"----\")\n if dists_mtx[2, ll] < 1000000000:\n sheet1.write(ll + 1, 3, dists_mtx[2, ll])\n else:\n sheet1.write(ll + 1, 3, \"----\")\n if dists_mtx[3, ll] < 1000000000:\n sheet1.write(ll + 1, 4, dists_mtx[3, ll])\n else:\n sheet1.write(ll + 1, 4, \"----\")\n if dists_mtx[4, ll] < 1000000000:\n sheet1.write(ll + 1, 5, dists_mtx[4, ll])\n else:\n sheet1.write(ll + 1, 5, \"----\")\n if dists_mtx[5, ll] < 1000000000:\n sheet1.write(ll + 1, 6, dists_mtx[5, ll])\n else:\n sheet1.write(ll + 1, 6, \"----\")\n\n if spts_clusters_flag[0] == 2:\n sheet2 = workbook._add_sheet(\"Overlap\")\n sheet2.write(0, 0, \"CH1_Id\")\n sheet2.write(0, 1, \"Volume\")\n sheet2.write(0, 2, \"z centroid\")\n sheet2.write(0, 3, \"x centroid\")\n sheet2.write(0, 4, \"y centroid\")\n sheet2.write(0, 5, \"CH2_Id\")\n sheet2.write(0, 6, \"Volume\")\n sheet2.write(0, 7, \"z centroid\")\n sheet2.write(0, 8, \"x centroid\")\n sheet2.write(0, 9, \"y centroid\")\n sheet2.write(0, 10, \"CH3_Id\")\n sheet2.write(0, 11, \"Volume\")\n sheet2.write(0, 12, \"z centroid\")\n sheet2.write(0, 13, \"x centroid\")\n sheet2.write(0, 14, \"y centroid\")\n\n sheet2.write(1, 16, \"CH2 on Clstrs\")\n sheet2.write(2, 16, \"CH2 not on Clstrs\")\n sheet2.write(3, 16, \"CH3 on Clstrs\")\n sheet2.write(4, 16, \"CH3 not on Clstrs\")\n\n sheet2.write(0, 17, \"Numb\")\n sheet2.write(0, 18, \"%\")\n\n numb_spts_ch2 = np.unique(spts_ch2_lbls[spts_ch2_lbls != 0]).size\n numb_spts_ch3 = np.unique(spts_ch3_lbls[spts_ch3_lbls != 0]).size\n ch2_on_clstr = spts_ch2_lbls * np.sign(spts_ch1_lbls)\n ch2_on_clstr = np.unique(ch2_on_clstr[ch2_on_clstr != 0]).size\n ch2_noton_clstr = numb_spts_ch2 - ch2_on_clstr\n ch3_on_clstr = spts_ch3_lbls * np.sign(spts_ch1_lbls)\n ch3_on_clstr = np.unique(ch3_on_clstr[ch3_on_clstr != 0]).size\n ch3_noton_clstr = numb_spts_ch3 - ch3_on_clstr\n\n sheet2.write(1, 17, np.int64(ch2_on_clstr))\n sheet2.write(2, 17, np.int64(ch2_noton_clstr))\n sheet2.write(3, 17, np.int64(ch3_on_clstr))\n sheet2.write(4, 17, np.int64(ch3_noton_clstr))\n sheet2.write(1, 18, np.float64(100 * ch2_on_clstr / numb_spts_ch2))\n sheet2.write(2, 18, np.float64(100 * ch2_noton_clstr / numb_spts_ch2))\n sheet2.write(3, 18, np.float64(100 * ch3_on_clstr / numb_spts_ch3))\n sheet2.write(4, 18, np.float64(100 * ch3_noton_clstr / numb_spts_ch3))\n\n row_idx = 0\n for bb in range(len(rgp_ch1[\"label\"])):\n sheet2.write(1 + row_idx, 0, \"Clst_\" + str(rgp_ch1[\"label\"][bb]))\n sheet2.write(1 + row_idx, 1, rgp_ch1[\"area\"][bb])\n sheet2.write(1 + row_idx, 2, rgp_ch1[\"centroid-0\"][bb])\n sheet2.write(1 + row_idx, 3, rgp_ch1[\"centroid-1\"][bb])\n sheet2.write(1 + row_idx, 4, rgp_ch1[\"centroid-2\"][bb])\n\n bff_ch2 = spts_ch2_lbls[rgp_ch1[\"coords\"][bb][:, 0], rgp_ch1[\"coords\"][bb][:, 1], rgp_ch1[\"coords\"][bb][:, 2]]\n bff_ch2 = np.unique(bff_ch2[bff_ch2 != 0])\n for dd in range(bff_ch2.size):\n iidd = np.where(rgp_ch2[\"label\"] == bff_ch2[dd])[0][0]\n sheet2.write(1 + row_idx + dd, 5, \"Spts_\" + str(rgp_ch2[\"label\"][iidd]))\n sheet2.write(1 + row_idx + dd, 6, rgp_ch2[\"area\"][iidd])\n sheet2.write(1 + row_idx + dd, 7, rgp_ch2[\"centroid-0\"][iidd])\n sheet2.write(1 + row_idx + dd, 8, rgp_ch2[\"centroid-1\"][iidd])\n sheet2.write(1 + row_idx + dd, 9, rgp_ch2[\"centroid-2\"][iidd])\n\n bff_ch3 = spts_ch3_lbls[rgp_ch1[\"coords\"][bb][:, 0], rgp_ch1[\"coords\"][bb][:, 1], rgp_ch1[\"coords\"][bb][:, 2]]\n bff_ch3 = np.unique(bff_ch3[bff_ch3 != 0])\n for pp in range(bff_ch3.size):\n ddii = np.where(rgp_ch3[\"label\"] == bff_ch3[pp])[0][0]\n sheet2.write(1 + row_idx + pp, 10, \"Spts_\" + str(rgp_ch3[\"label\"][ddii]))\n sheet2.write(1 + row_idx + pp, 11, rgp_ch3[\"area\"][ddii])\n sheet2.write(1 + row_idx + pp, 12, rgp_ch3[\"centroid-0\"][ddii])\n sheet2.write(1 + row_idx + pp, 13, rgp_ch3[\"centroid-1\"][ddii])\n sheet2.write(1 + row_idx + pp, 14, rgp_ch3[\"centroid-2\"][ddii])\n\n row_idx += np.max([bff_ch2.size, bff_ch3.size])\n\n workbook.close()\n\n mtx2show = np.zeros(spts_ch2.shape + (3,), dtype=np.uint8)\n mtx2show[:, :, :, 0] = 125 * np.sign(nucs_dapi) * (1 - spts_ch1_fin) * (1 - spts_ch2_fin) * (1 - spts_ch3_fin)\n mtx2show[:, :, :, 1] = 125 * np.sign(nucs_dapi) * (1 - spts_ch1_fin) * (1 - spts_ch2_fin) * (1 - spts_ch3_fin)\n mtx2show[:, :, :, 2] = 125 * np.sign(nucs_dapi) * (1 - spts_ch1_fin) * (1 - spts_ch2_fin) * (1 - spts_ch3_fin)\n mtx2show[:, :, :, 1] += 255 * spts_ch1_fin\n mtx2show[:, :, :, 0] += 255 * spts_ch2_fin\n mtx2show[:, :, :, 2] += 255 * spts_ch3_fin\n # pg.image(mtx2show)\n\n self.mtx2show = mtx2show\n self.nucs_dapi = nucs_dapi\n\n\nclass ProgressBar(QtWidgets.QWidget):\n \"\"\"Simple progress bar widget\"\"\"\n def __init__(self, parent=None, total1=20):\n super(ProgressBar, self).__init__(parent)\n self.name_line1 = QtWidgets.QLineEdit()\n\n self.progressbar1 = QtWidgets.QProgressBar()\n self.progressbar1.setMinimum(1)\n self.progressbar1.setMaximum(total1)\n\n main_layout = QtWidgets.QGridLayout()\n main_layout.addWidget(self.progressbar1, 0, 0)\n\n self.setLayout(main_layout)\n self.setWindowTitle(\"Progress\")\n self.setGeometry(500, 300, 300, 50)\n\n def update_progressbar1(self, val1):\n \"\"\"First progress bar updater\"\"\"\n self.progressbar1.setValue(val1)\n QtWidgets.qApp.processEvents()\n\n\n\n\n","sub_path":"ModifCrossInfo.py","file_name":"ModifCrossInfo.py","file_ext":"py","file_size_in_byte":20126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"244026773","text":"from rest_framework import relations, renderers, serializers, status\nfrom rest_framework.settings import api_settings\nfrom rest_framework_json_api import encoders\nfrom rest_framework_json_api.utils import (\n get_related_field, is_related_many,\n model_from_obj, model_to_resource_type\n)\nfrom django.core import urlresolvers\nfrom django.core.exceptions import NON_FIELD_ERRORS\nfrom django.utils import encoding, six\nfrom django.utils.six.moves.urllib.parse import urlparse, urlunparse\n\n\nclass WrapperNotApplicable(ValueError):\n\n def __init__(self, *args, **kwargs):\n self.data = kwargs.pop('data', None)\n self.renderer_context = kwargs.pop('renderer_context', None)\n\n return super(WrapperNotApplicable, self).__init__(*args, **kwargs)\n\n\nclass JsonApiMixin(object):\n convert_by_name = {\n 'id': 'convert_to_text',\n api_settings.URL_FIELD_NAME: 'rename_to_href',\n }\n\n convert_by_type = {\n relations.PrimaryKeyRelatedField: 'handle_related_field',\n relations.HyperlinkedRelatedField: 'handle_url_field',\n serializers.ModelSerializer: 'handle_nested_serializer',\n }\n dict_class = dict\n encoder_class = encoders.JSONEncoder\n media_type = 'application/vnd.api+json'\n wrappers = [\n 'wrap_empty_response',\n 'wrap_parser_error',\n 'wrap_field_error',\n 'wrap_generic_error',\n 'wrap_options',\n 'wrap_paginated',\n 'wrap_default'\n ]\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n \"\"\"Convert native data to JSON API\n\n Tries each of the methods in `wrappers`, using the first successful\n one, or raises `WrapperNotApplicable`.\n \"\"\"\n\n wrapper = None\n success = False\n\n for wrapper_name in self.wrappers:\n wrapper_method = getattr(self, wrapper_name)\n try:\n wrapper = wrapper_method(data, renderer_context)\n except WrapperNotApplicable:\n pass\n else:\n success = True\n break\n\n if not success:\n raise WrapperNotApplicable(\n 'No acceptable wrappers found for response.',\n data=data, renderer_context=renderer_context)\n\n renderer_context[\"indent\"] = 4\n\n return super(JsonApiMixin, self).render(\n data=wrapper,\n accepted_media_type=accepted_media_type,\n renderer_context=renderer_context)\n\n def wrap_empty_response(self, data, renderer_context):\n \"\"\"\n Pass-through empty responses\n\n 204 No Content includes an empty response\n \"\"\"\n\n if data is not None:\n raise WrapperNotApplicable('Data must be empty.')\n\n return data\n\n def wrap_parser_error(self, data, renderer_context):\n \"\"\"\n Convert parser errors to the JSON API Error format\n\n Parser errors have a status code of 400, like field errors, but have\n the same native format as generic errors. Also, the detail message is\n often specific to the input, so the error is listed as a 'detail'\n rather than a 'title'.\n \"\"\"\n\n response = renderer_context.get(\"response\", None)\n status_code = response and response.status_code\n\n if status_code != 400:\n raise WrapperNotApplicable('Status code must be 400.')\n\n if list(data.keys()) != ['detail']:\n raise WrapperNotApplicable('Data must only have \"detail\" key.')\n\n # Probably a parser error, unless `detail` is a valid field\n view = renderer_context.get(\"view\", None)\n model = self.model_from_obj(view)\n\n if 'detail' in model._meta.get_all_field_names():\n raise WrapperNotApplicable()\n\n return self.wrap_error(\n data, renderer_context, keys_are_fields=False,\n issue_is_title=False)\n\n def wrap_field_error(self, data, renderer_context):\n \"\"\"\n Convert field error native data to the JSON API Error format\n\n See the note about the JSON API Error format on `wrap_error`.\n\n The native format for field errors is a dictionary where the keys are\n field names (or 'non_field_errors' for additional errors) and the\n values are a list of error strings:\n\n {\n \"min\": [\n \"min must be greater than 0.\",\n \"min must be an even number.\"\n ],\n \"max\": [\"max must be a positive number.\"],\n \"non_field_errors\": [\n \"Select either a range or an enumeration, not both.\"]\n }\n\n It is rendered into this JSON API error format:\n\n {\n \"errors\": [{\n \"status\": \"400\",\n \"path\": \"/min\",\n \"detail\": \"min must be greater than 0.\"\n },{\n \"status\": \"400\",\n \"path\": \"/min\",\n \"detail\": \"min must be an even number.\"\n },{\n \"status\": \"400\",\n \"path\": \"/max\",\n \"detail\": \"max must be a positive number.\"\n },{\n \"status\": \"400\",\n \"path\": \"/-\",\n \"detail\": \"Select either a range or an enumeration, not both.\"\n }]\n }\n \"\"\"\n response = renderer_context.get(\"response\", None)\n status_code = response and response.status_code\n if status_code != 400:\n raise WrapperNotApplicable('Status code must be 400.')\n\n return self.wrap_error(\n data, renderer_context, keys_are_fields=True, issue_is_title=False)\n\n def wrap_generic_error(self, data, renderer_context):\n \"\"\"\n Convert generic error native data using the JSON API Error format\n\n See the note about the JSON API Error format on `wrap_error`.\n\n The native format for errors that are not bad requests, such as\n authentication issues or missing content, is a dictionary with a\n 'detail' key and a string value:\n\n {\n \"detail\": \"Authentication credentials were not provided.\"\n }\n\n This is rendered into this JSON API error format:\n\n {\n \"errors\": [{\n \"status\": \"403\",\n \"title\": \"Authentication credentials were not provided\"\n }]\n }\n \"\"\"\n response = renderer_context.get(\"response\", None)\n status_code = response and response.status_code\n is_error = (\n status.is_client_error(status_code) or\n status.is_server_error(status_code)\n )\n if not is_error:\n raise WrapperNotApplicable(\"Status code must be 4xx or 5xx.\")\n\n return self.wrap_error(\n data, renderer_context, keys_are_fields=False, issue_is_title=True)\n\n def wrap_error(\n self, data, renderer_context, keys_are_fields, issue_is_title):\n \"\"\"Convert error native data to the JSON API Error format\n\n JSON API has a different format for errors, but Django REST Framework\n doesn't have a separate rendering path for errors. This results in\n some guesswork to determine if data is an error, what kind, and how\n to handle it.\n\n As of August 2014, there is not a consensus about the error format in\n JSON API. The format documentation defines an \"errors\" collection, and\n some possible fields for that collection, but without examples for\n common cases. If and when consensus is reached, this format will\n probably change.\n \"\"\"\n\n response = renderer_context.get(\"response\", None)\n status_code = str(response and response.status_code)\n\n errors = []\n for field, issues in data.items():\n if isinstance(issues, six.string_types):\n issues = [issues]\n for issue in issues:\n error = self.dict_class()\n error[\"status\"] = status_code\n\n if issue_is_title:\n error[\"title\"] = issue\n else:\n error[\"detail\"] = issue\n\n if keys_are_fields:\n if field in ('non_field_errors', NON_FIELD_ERRORS):\n error[\"path\"] = '/-'\n else:\n error[\"path\"] = '/' + field\n\n errors.append(error)\n wrapper = self.dict_class()\n wrapper[\"errors\"] = errors\n return wrapper\n\n def wrap_options(self, data, renderer_context):\n '''Wrap OPTIONS data as JSON API meta value'''\n request = renderer_context.get(\"request\", None)\n method = request and getattr(request, 'method')\n if method != 'OPTIONS':\n raise WrapperNotApplicable(\"Request method must be OPTIONS\")\n\n wrapper = self.dict_class()\n wrapper[\"meta\"] = data\n return wrapper\n\n def wrap_paginated(self, data, renderer_context):\n \"\"\"Convert paginated data to JSON API with meta\"\"\"\n\n pagination_keys = ['count', 'next', 'previous', 'results']\n for key in pagination_keys:\n if not (data and key in data):\n raise WrapperNotApplicable('Not paginated results')\n\n view = renderer_context.get(\"view\", None)\n model = self.model_from_obj(view)\n resource_type = self.model_to_resource_type(model)\n\n try:\n from rest_framework.utils.serializer_helpers import ReturnList\n\n results = ReturnList(\n data[\"results\"],\n serializer=data.serializer.fields[\"results\"],\n )\n except ImportError:\n results = data[\"results\"]\n\n # Use default wrapper for results\n wrapper = self.wrap_default(results, renderer_context)\n\n # Add pagination metadata\n pagination = self.dict_class()\n\n pagination['previous'] = data['previous']\n pagination['next'] = data['next']\n pagination['count'] = data['count']\n\n wrapper.setdefault('meta', self.dict_class())\n\n wrapper['meta'].setdefault('pagination', self.dict_class())\n wrapper['meta']['pagination'].setdefault(\n resource_type, self.dict_class()).update(pagination)\n\n return wrapper\n\n def wrap_default(self, data, renderer_context):\n \"\"\"Convert native data to a JSON API resource collection\n\n This wrapper expects a standard DRF data object (a dict-like\n object with a `fields` dict-like attribute), or a list of\n such data objects.\n \"\"\"\n\n wrapper = self.dict_class()\n view = renderer_context.get(\"view\", None)\n request = renderer_context.get(\"request\", None)\n\n model = self.model_from_obj(view)\n resource_type = self.model_to_resource_type(model)\n\n if isinstance(data, list):\n many = True\n resources = data\n else:\n many = False\n resources = [data]\n\n items = []\n links = self.dict_class()\n linked = self.dict_class()\n meta = self.dict_class()\n\n for resource in resources:\n converted = self.convert_resource(resource, data, request)\n item = converted.get('data', {})\n linked_ids = converted.get('linked_ids', {})\n if linked_ids:\n item[\"links\"] = linked_ids\n items.append(item)\n\n links.update(converted.get('links', {}))\n linked.update(converted.get('linked', {}))\n meta.update(converted.get('meta', {}))\n\n if many:\n wrapper[resource_type] = items\n else:\n wrapper[resource_type] = items[0]\n\n if links:\n links = self.prepend_links_with_name(links, resource_type)\n wrapper[\"links\"] = links\n\n if linked:\n wrapper[\"linked\"] = linked\n\n if meta:\n wrapper[\"meta\"] = meta\n\n return wrapper\n\n def convert_resource(self, resource, data, request):\n fields = self.fields_from_resource(resource, data)\n\n if not fields:\n raise WrapperNotApplicable('Items must have a fields attribute.')\n\n data = self.dict_class()\n linked_ids = self.dict_class()\n links = self.dict_class()\n linked = self.dict_class()\n meta = self.dict_class()\n\n for field_name, field in six.iteritems(fields):\n converted = None\n\n if field_name in self.convert_by_name:\n converter_name = self.convert_by_name[field_name]\n converter = getattr(self, converter_name)\n converted = converter(resource, field, field_name, request)\n else:\n related_field = get_related_field(field)\n\n for field_type, converter_name in \\\n six.iteritems(self.convert_by_type):\n if isinstance(related_field, field_type):\n converter = getattr(self, converter_name)\n converted = converter(\n resource, field, field_name, request)\n break\n\n if converted:\n data.update(converted.pop(\"data\", {}))\n linked_ids.update(converted.pop(\"linked_ids\", {}))\n links.update(converted.get(\"links\", {}))\n linked.update(converted.get(\"linked\", {}))\n meta.update(converted.get(\"meta\", {}))\n else:\n data[field_name] = resource[field_name]\n\n return {\n 'data': data,\n 'linked_ids': linked_ids,\n 'links': links,\n 'linked': linked,\n 'meta': meta,\n }\n\n def convert_to_text(self, resource, field, field_name, request):\n data = self.dict_class()\n data[field_name] = encoding.force_text(resource[field_name])\n return {\"data\": data}\n\n def rename_to_href(self, resource, field, field_name, request):\n data = self.dict_class()\n data['href'] = resource[field_name]\n return {\"data\": data}\n\n def prepend_links_with_name(self, links, name):\n changed_links = links.copy()\n\n for link_name, link_obj in six.iteritems(links):\n prepended_name = \"%s.%s\" % (name, link_name)\n link_template = \"{%s}\" % link_name\n prepended_template = \"{%s}\" % prepended_name\n\n updated_obj = changed_links[link_name]\n\n if \"href\" in link_obj:\n updated_obj[\"href\"] = link_obj[\"href\"].replace(\n link_template, prepended_template)\n\n changed_links[prepended_name] = changed_links[link_name]\n del changed_links[link_name]\n\n return changed_links\n\n def handle_nested_serializer(self, resource, field, field_name, request):\n serializer_field = get_related_field(field)\n\n if hasattr(serializer_field, \"opts\"):\n model = serializer_field.opts.model\n else:\n model = serializer_field.Meta.model\n\n resource_type = self.model_to_resource_type(model)\n\n linked_ids = self.dict_class()\n links = self.dict_class()\n linked = self.dict_class()\n linked[resource_type] = []\n\n if is_related_many(field):\n items = resource[field_name]\n else:\n items = [resource[field_name]]\n\n obj_ids = []\n\n resource.serializer = serializer_field\n\n for item in items:\n converted = self.convert_resource(item, resource, request)\n linked_obj = converted[\"data\"]\n linked_ids = converted.pop(\"linked_ids\", {})\n\n if linked_ids:\n linked_obj[\"links\"] = linked_ids\n\n obj_ids.append(converted[\"data\"][\"id\"])\n\n field_links = self.prepend_links_with_name(\n converted.get(\"links\", {}), resource_type)\n\n field_links[field_name] = {\n \"type\": resource_type,\n }\n\n if \"href\" in converted[\"data\"]:\n url_field_name = api_settings.URL_FIELD_NAME\n url_field = serializer_field.fields[url_field_name]\n\n field_links[field_name][\"href\"] = self.url_to_template(\n url_field.view_name, request, field_name,\n )\n\n links.update(field_links)\n\n linked[resource_type].append(linked_obj)\n\n if is_related_many(field):\n linked_ids[field_name] = obj_ids\n else:\n linked_ids[field_name] = obj_ids[0]\n\n return {\"linked_ids\": linked_ids, \"links\": links, \"linked\": linked}\n\n def handle_related_field(self, resource, field, field_name, request):\n links = self.dict_class()\n linked_ids = self.dict_class()\n\n related_field = get_related_field(field)\n\n model = self.model_from_obj(related_field)\n resource_type = self.model_to_resource_type(model)\n\n if field_name in resource:\n links[field_name] = {\n \"type\": resource_type,\n }\n\n if is_related_many(field):\n link_data = [\n encoding.force_text(pk) for pk in resource[field_name]]\n elif resource[field_name]:\n link_data = encoding.force_text(resource[field_name])\n else:\n link_data = None\n\n linked_ids[field_name] = link_data\n\n return {\"linked_ids\": linked_ids, \"links\": links}\n\n def handle_url_field(self, resource, field, field_name, request):\n links = self.dict_class()\n linked_ids = self.dict_class()\n\n related_field = get_related_field(field)\n\n model = self.model_from_obj(related_field)\n resource_type = self.model_to_resource_type(model)\n\n links[field_name] = {\n \"href\": self.url_to_template(related_field.view_name,\n request,\n field_name),\n \"type\": resource_type,\n }\n\n if field_name in resource:\n linked_ids[field_name] = self.url_to_pk(\n resource[field_name], field)\n\n return {\"linked_ids\": linked_ids, \"links\": links}\n\n def url_to_pk(self, url_data, field):\n if is_related_many(field):\n try:\n obj_list = field.to_internal_value(url_data)\n except AttributeError:\n obj_list = [field.from_native(url) for url in url_data]\n\n return [encoding.force_text(obj.pk) for obj in obj_list]\n\n if url_data:\n try:\n obj = field.to_internal_value(url_data)\n except AttributeError:\n obj = field.from_native(url_data)\n\n return encoding.force_text(obj.pk)\n else:\n return None\n\n def url_to_template(self, view_name, request, template_name):\n resolver = urlresolvers.get_resolver(None)\n info = resolver.reverse_dict[view_name]\n\n path_template = info[0][0][0]\n # FIXME: what happens when URL has more than one dynamic values?\n # e.g. nested relations: manufacturer/%(id)s/cars/%(card_id)s\n path = path_template % {info[0][0][1][0]: '{%s}' % template_name}\n\n parsed_url = urlparse(request.build_absolute_uri())\n\n return urlunparse(\n [parsed_url.scheme, parsed_url.netloc, path, '', '', '']\n )\n\n def fields_from_resource(self, resource, data):\n if hasattr(data, \"serializer\"):\n resource = data.serializer\n\n if hasattr(resource, \"child\"):\n resource = resource.child\n\n return getattr(resource, \"fields\", None)\n\n def model_to_resource_type(self, model):\n return model_to_resource_type(model)\n\n def model_from_obj(self, obj):\n return model_from_obj(obj)\n\n\nclass JsonApiRenderer(JsonApiMixin, renderers.JSONRenderer):\n pass\n","sub_path":"rest_framework_json_api/renderers.py","file_name":"renderers.py","file_ext":"py","file_size_in_byte":19869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"151000874","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, Dataset, TensorDataset\nfrom torch.optim import *\nimport torchvision\nimport torchvision.transforms as transforms\nimport time\nimport matplotlib.pyplot as plt\n\n\n\ndef train(model, iterator, optimizer, criterion, device):\n total = 0\n correct = 0\n epoch_loss = 0\n epoch_acc = 0\n predicted_list = []\n model.train()\n \n for batch, labels in iterator:\n \n #Move tensors to the configured device\n batch = batch.to(device)\n labels = labels.to(device)\n \n \n #Forward pass\n outputs = model(batch.float())\n outputs = outputs.to(device)\n \n loss = criterion(outputs, labels).to(device)\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n #check accuracy\n predictions = model(batch.float())\n _, predicted = torch.max(predictions.data, 1) #returns max value, indices\n total += labels.size(0) #keep track of total\n correct += (predicted == labels).sum().item() #.item() give the raw number\n acc = 100 * (correct / total)\n \n epoch_loss += loss.item()\n epoch_acc = acc\n predicted_list.append(predicted)\n \n return epoch_loss / len(iterator), epoch_acc, predicted_list\n\n#======================================================================\ndef evaluate(model, iterator, criterion , device):\n \n total = 0\n correct = 0\n epoch_loss = 0\n epoch_acc = 0\n predicted_list = []\n labels_list = []\n \n model.eval()\n \n with torch.no_grad():\n \n for batch, labels in iterator:\n \n #Move tensors to the configured device\n batch = batch.to(device)\n labels = labels.to(device)\n \n #print(labels)\n \n\n predictions = model(batch.float())\n loss = criterion(predictions, labels)\n \n \n _, predicted = torch.max(predictions.data, 1) #returns max value, indices\n #print(predicted)\n \n total += labels.size(0) #keep track of total\n correct += (predicted == labels).sum().item() #.item() give the raw number\n acc = 100 * (correct / total)\n \n epoch_loss += loss.item()\n epoch_acc += acc\n \n labels_list.append(labels)\n predicted_list.append(predicted)\n \n\n return epoch_loss / len(iterator), epoch_acc / len(iterator) ,predicted_list, labels_list\n\n\n#======================================================================\n\n# define a time function useful for calculating time\ndef epoch_time(start_time, end_time):\n elapsed_time = end_time - start_time\n elapsed_mins = int(elapsed_time / 60)\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n return elapsed_mins, elapsed_secs\n\n\n\ndef do_plot(train_losses, valid_losses):\n plt.figure(figsize=(25,5))\n# clear_output(wait=True)\n plt.plot(train_losses, label='train loss')\n plt.plot(valid_losses, label='valid_loss')\n plt.title('Classification based Encoder loss')\n plt.legend()\n plt.show()\n\ndef save_loss_graph(_train_losses, _valid_losses, _path, _file):\n import matplotlib as mpl\n mpl.use('agg')\n _fig = plt.figure()\n plt.figure(figsize=(25,5))\n _ax = plt.plot(_train_losses, label='train loss')\n plt.plot(_valid_losses, label='valid_loss')\n plt.title('Classification based Encoder loss')\n plt.legend()\n plt.savefig(f'{_path}{_file}-loss.png')\n plt.close(_fig)\n\ndef save_acc_graph(_train_acc, _valid_acc, _path, _file):\n import matplotlib as mpl\n mpl.use('agg')\n _fig = plt.figure()\n plt.figure(figsize=(25,5))\n plt.plot(_train_acc, 'r' , label='train acc')\n plt.plot(_valid_acc, 'g' , label='valid acc')\n plt.title('Accuracy graph')\n plt.legend()\n plt.savefig(f'{_path}{_file}-acc.png')\n plt.close(_fig)\n","sub_path":"Reconstruction/experiment/Nice/libs/train_utilities.py","file_name":"train_utilities.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"593448974","text":"try:\n import cStringIO as StringIO\nexcept ImportError:\n import StringIO\n\nimport csv\n\nfrom django.http import HttpResponse\nfrom django.utils.encoding import smart_unicode\nfrom django.utils.xmlutils import SimplerXMLGenerator\n\nfrom piston.emitters import Emitter, XMLEmitter\nfrom django.utils.encoding import smart_str\nfrom unidecode import unidecode\n\n\nclass CustomXMLEmitter(XMLEmitter):\n \"\"\"\n Overides the default xml generator\n Expects a dict object,\n the key of the object will be used as the opening tag\n \"\"\"\n\n def _to_xml(self, xml, data):\n if isinstance(data, (list, tuple)):\n for item in data:\n self._to_xml(xml, item)\n elif isinstance(data, dict):\n for key, value in data.iteritems():\n xml.startElement(key, {})\n self._to_xml(xml, value)\n xml.endElement(key)\n else:\n xml.characters(smart_unicode(data))\n\n def render(self, request):\n stream = StringIO.StringIO()\n\n xml = SimplerXMLGenerator(stream, \"utf-8\")\n xml.startDocument()\n self._to_xml(xml, self.construct())\n xml.endDocument()\n\n return stream.getvalue()\n\n\nclass CSVEmitter(Emitter):\n \"\"\"\n Emitter for exporting to CSV (excel dialect).\n \"\"\"\n def get_keys(self, input_dict):\n keys = []\n for item in input_dict.items():\n if isinstance(item[1], dict):\n keys.extend(self.get_keys(item[1]))\n else:\n keys.append(item[0])\n return keys\n\n def get_values(self, input_dict):\n for item in input_dict.items():\n if isinstance(item[1], dict):\n input_dict.update(self.get_values(input_dict.pop(item[0])))\n else:\n input_dict[item[0]] = unidecode(smart_str(item[1]))\n return input_dict\n\n def render(self, request):\n #response = StringIO.StringIO()\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=download.csv'\n\n content = self.construct()\n\n if isinstance(content, dict):\n content = content.values()[0]\n\n if content:\n keys = self.get_keys(content[0])\n\n if keys:\n writer = csv.DictWriter(response, keys, dialect='excel')\n headers = dict((n, n) for n in keys)\n writer.writerow(headers)\n for row in content:\n writer.writerow(self.get_values(row))\n\n return response\n\nEmitter.register('xml', CustomXMLEmitter, 'text/xml; charset=utf-8')\nEmitter.register('csv', CSVEmitter, 'text/csv; charset=utf-8')\n","sub_path":"api/emitters.py","file_name":"emitters.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"160668765","text":"\"\"\"\nThe main client class, handles all client functionality\n\"\"\"\n\n\nfrom abc import ABCMeta, abstractmethod\nimport socket\nimport logging\n\nfrom submarines_client import messages, constants, exceptions, protocol_utils\nfrom submarines_client.messages_codec import BaseMessagesCodec, MessagesCodec\nfrom submarines_client.messages import SubmarineMessageType\n\n\nclass BaseSubmarinesClient(metaclass=ABCMeta):\n \"\"\"\n The main client class, handles all client functionality\n \"\"\"\n\n @classmethod\n @abstractmethod\n def listen(cls, listening_port: int):\n \"\"\"\n Start listen to incoming tcp connections\n\n :param listening_port: The listening port to use\n :return: A client instance (on listen mode)\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def wait_for_game(self):\n \"\"\"\n Wait for a game request, and accept it\n Note: this is a blocking method, it will exit only\n when a game connection is established\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def invite_player(self, player_host: str, player_port: int) -> bool:\n \"\"\"\n Invite a player for a game\n Note: this is a blocking method, it will exit only\n when a response is received or an error is raised\n\n :param player_host: The player's host\n :param player_port: The player's port\n :return: whether the player accepted the game invite\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def send_message(self, message: messages.BaseSubmarinesMessage):\n \"\"\"\n send a message to the connected player\n\n :param message: The message you wish to send\n :raise NotConnectedError: No player is connected to the client\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def receive_message(self, expected_type: SubmarineMessageType) -> messages.BaseSubmarinesMessage:\n \"\"\"\n Receive a message from the connected player\n\n :param expected_type: optional, an expected message type\n :return: The decoded message\n :raise NotConnectedError: No player is connected to the client\n :raise ProtocolException: if the message is not expected type\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def __enter__(self):\n \"\"\"\n The client's entering point\n\n :return: The client\n \"\"\"\n\n raise NotImplementedError()\n\n @abstractmethod\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n The client's exit point (used for cleanup)\n\n :return: Should the exception be suppressed\n \"\"\"\n\n raise NotImplementedError()\n\n\nclass TCPSubmarinesClient(BaseSubmarinesClient):\n \"\"\"\n The main client class, handles all client functionality,\n using tcp connection\n \"\"\"\n\n def __init__(self,\n messages_codec: BaseMessagesCodec,\n listening_socket: socket.socket,\n game_socket: socket.socket = None):\n \"\"\"\n Initializing a client\n\n :param messages_codec: The messages codec of the client\n :param listening_socket: The socket in which you listen to incoming requests\n :param game_socket: A game socket, this socket has to be in a game session,\n means a game request and response was passed on this socket\n \"\"\"\n\n self._messages_codec = messages_codec\n self._listening_socket = listening_socket\n self._game_socket = game_socket\n self._logger = logging.getLogger(constants.LOGGER_NAME)\n\n @classmethod\n def listen(cls,\n listening_port: int = constants.Network.DEFAULT_PORT,\n messages_codec: BaseMessagesCodec = MessagesCodec()):\n \"\"\"\n Start listen to incoming tcp connections\n\n :param listening_port: The listening port to use\n :param messages_codec: The messages codec for the client\n :return: A client instance (on listen mode)\n \"\"\"\n\n try:\n listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listening_socket.bind((constants.Network.PUBLIC_IP, listening_port))\n listening_socket.listen(1)\n\n return cls(messages_codec=messages_codec, listening_socket=listening_socket)\n except socket.error:\n raise\n\n def wait_for_game(self):\n \"\"\"\n Wait for a game request, and accept it\n Note: this is a blocking method, it will exit only\n when a game connection is established\n \"\"\"\n\n while not self._game_socket:\n try:\n # accept connection\n self._game_socket, address = self._listening_socket.accept()\n\n # receive game request\n self.receive_message(SubmarineMessageType.GAME_REQUEST)\n self._logger.info('Incoming game request: ', f'from {address}')\n\n # send game reply\n self.send_message(messages.GameReplyMessage())\n self._logger.info('Game reply sent: ', 'game starts')\n except exceptions.ProtocolException as pe:\n self._logger.warning('Protocol error: ', pe)\n self._game_socket = None\n except socket.error as se:\n self._logger.warning('Network error: ', se)\n self._game_socket = None\n\n def invite_player(self, player_host: str, player_port: int = constants.Network.DEFAULT_PORT) -> bool:\n \"\"\"\n Invite a player for a game\n Note: this is a blocking method, it will exit only\n when a response is received or an error is raised\n\n :param player_host: The player's host\n :param player_port: The player's port\n :return: whether the player accepted the game invite\n \"\"\"\n\n try:\n # Connect to player\n self._game_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._game_socket.connect((player_host, player_port))\n\n # send game request\n self.send_message(messages.GameRequestMessage())\n\n # receive game reply\n game_reply: messages.GameReplyMessage = self.receive_message(SubmarineMessageType.GAME_REPLY)\n return game_reply.response\n except exceptions.ProtocolException:\n raise\n except socket.error:\n raise\n\n def send_message(self, message: messages.BaseSubmarinesMessage):\n \"\"\"\n send a message to the connected player\n\n :param message: The message you wish to send\n :raise NotConnectedError: No player is connected to the client\n \"\"\"\n\n encoded_message = self._messages_codec.encode_message(message)\n self._game_socket.send(encoded_message)\n\n def receive_message(self, expected_type: SubmarineMessageType = None) -> messages.BaseSubmarinesMessage:\n \"\"\"\n Receive a message from the connected player\n\n :param expected_type: optional, an expected message type\n :return: The decoded message\n :raise NotConnectedError: No player is connected to the client\n :raise ProtocolException: if the message is not expected type\n \"\"\"\n\n encoded_message = bytes()\n\n try:\n new_data = self._game_socket.recv(constants.Network.BUFFER_SIZE)\n\n while new_data:\n encoded_message += new_data\n\n if len(new_data) < constants.Network.BUFFER_SIZE:\n break\n\n new_data = self._game_socket.recv(constants.Network.BUFFER_SIZE)\n\n message = self._messages_codec.decode_message(encoded_message)\n\n if message.get_message_type() == SubmarineMessageType.ERROR:\n raise message.exception\n\n if expected_type:\n protocol_utils.insure_message_type(message, expected_type)\n\n return message\n\n except exceptions.ProtocolException:\n raise\n except socket.error:\n raise\n\n def __enter__(self):\n \"\"\"\n The client's entering point\n\n :return: The client\n \"\"\"\n\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n The client's exit point (used for cleanup)\n\n :return: Should the exception be suppressed\n \"\"\"\n\n if self._game_socket:\n self._game_socket.close()\n\n if self._listening_socket:\n self._listening_socket.close()\n\n return False\n","sub_path":"submarines_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"606144548","text":"from __future__ import annotations\n\nimport math\nimport random\nimport time\nfrom threading import Condition\n\nfrom ibapi.client import EClient\nfrom ibapi.commission_report import CommissionReport\nfrom ibapi.common import BarData, ListOfHistoricalTickLast, OrderId, TickerId, TickAttribLast, TickAttrib, \\\n HistoricalTickLast\nfrom ibapi.contract import Contract, ContractDetails\nfrom ibapi.ticktype import TickType\nfrom ibapi.wrapper import EWrapper\nfrom pandas import DataFrame\n\nfrom se2.domain.account import *\nfrom se2.domain.time_series import HistoryDataQueryCommand, TSData, Column, Asset, RTTimeSeriesType, \\\n BarHistoryTimeSeriesType, TSTypeRegistry\n\nclient: IBClient = None\n\n\ndef initialize(host: str, port: int, client_id: int):\n \"\"\"\n 初始化ib\n :param host:\n :param port:\n :param client_id:\n :return:\n \"\"\"\n global client\n if client:\n raise RuntimeError(\"client已经被初始化了\")\n client = IBClient(host, port, client_id)\n # 注册时序类型\n TSTypeRegistry.register(IBMinBar())\n TSTypeRegistry.register(IBCurrentPrice())\n TSTypeRegistry.register(IBAdjustedDailyBar())\n\n\nclass IBAccount(AbstractAccount):\n def match(self, data):\n raise NotImplementedError\n\n def do_place_order(self, order: Order):\n pass\n\n def do_cancel_order(self, order: Order):\n pass\n\n def do_update_order_price(self, order, new_price):\n pass\n\n def valid_scope(self, codes):\n pass\n\n\nclass Request(object):\n id_to_request = {}\n\n def __init__(self):\n self.condition: Condition = Condition()\n self.req_id = self._random_id()\n self.resp = None\n Request.id_to_request[self.req_id] = self\n\n def _random_id(self):\n while True:\n k = random.randint(0, 100000000)\n if k not in Request.id_to_request:\n return k\n\n @classmethod\n def new_request(cls):\n return Request()\n\n @classmethod\n def clear(cls, req_id):\n return Request.id_to_request.pop(req_id)\n\n @classmethod\n def find(cls, reqId):\n return Request.id_to_request[reqId]\n\n\nclass ClientStatusCallback(metaclass=ABCMeta):\n @abstractmethod\n def re_connect(self):\n pass\n\n\nclass IBClient(EWrapper):\n clients_map: Mapping[str, IBClient] = {}\n\n def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib):\n super().tickPrice(reqId, tickType, price, attrib)\n if self.market_data_subscriber:\n self.market_data_subscriber.tickPrice(reqId, tickType, price, attrib)\n\n def tickSize(self, reqId: TickerId, tickType: TickType, size: int):\n super().tickSize(reqId, tickType, size)\n if self.market_data_subscriber:\n self.market_data_subscriber.tickSize(reqId, tickType, size)\n\n def tickString(self, reqId: TickerId, tickType: TickType, value: str):\n super().tickString(reqId, tickType, value)\n if self.market_data_subscriber:\n self.market_data_subscriber.tickString(reqId, tickType, value)\n\n def error(self, reqId: TickerId, errorCode: int, errorString: str):\n super().error(reqId, errorCode, errorString)\n\n def tickByTickAllLast(self, reqId: int, tickType: int, time: int, price: float, size: int,\n tickAttribLast: TickAttribLast, exchange: str, specialConditions: str):\n try:\n super().tickByTickAllLast(reqId, tickType, time, price, size, tickAttribLast, exchange, specialConditions)\n if self.tick_subscriber:\n self.tick_subscriber.tickByTickAllLast(reqId, tickType, time, price, size, tickAttribLast,\n exchange, specialConditions)\n except:\n import traceback\n logging.error(\"{}\".format(traceback.format_exc()))\n\n def execDetails(self, reqId: int, contract: Contract, execution: Execution):\n try:\n super().execDetails(reqId, contract, execution)\n if self.account_subscriber:\n self.account_subscriber.execDetails(reqId, contract, execution)\n except:\n import traceback\n logging.error(\"{}\".format(traceback.format_exc()))\n\n def commissionReport(self, commissionReport: CommissionReport):\n try:\n super().commissionReport(commissionReport)\n if self.account_subscriber:\n self.account_subscriber.commissionReport(commissionReport)\n except:\n import traceback\n logging.error(\"{}\".format(traceback.format_exc()))\n\n def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float,\n permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float):\n try:\n super().orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice,\n clientId,\n whyHeld, mktCapPrice)\n if self.account_subscriber:\n self.account_subscriber.orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId,\n lastFillPrice, clientId, whyHeld, mktCapPrice)\n except:\n import traceback\n logging.error(\"{}\".format(traceback.format_exc()))\n\n def historicalData(self, reqId: int, bar: BarData):\n super().historicalData(reqId, bar)\n req = Request.find(reqId)\n if not req.resp:\n req.resp = [bar]\n else:\n req.resp.append(bar)\n\n def historicalDataEnd(self, reqId: int, start: str, end: str):\n super().historicalDataEnd(reqId, start, end)\n req = Request.find(reqId)\n if req.condition.acquire():\n req.condition.notifyAll()\n req.condition.release()\n\n def historicalTicksLast(self, reqId: int, ticks: ListOfHistoricalTickLast, done: bool):\n super().historicalTicksLast(reqId, ticks, done)\n req = Request.find(reqId)\n if req.resp:\n req.resp.extend(ticks)\n else:\n req.resp = ticks\n if done:\n if req.condition.acquire():\n req.condition.notifyAll()\n req.condition.release()\n\n def contractDetails(self, reqId: int, contractDetails: ContractDetails):\n super().contractDetails(reqId, contractDetails)\n req = Request.find(reqId)\n if not req.resp:\n req.resp = [contractDetails.contract]\n else:\n req.resp.append(contractDetails.contract)\n\n def contractDetailsEnd(self, reqId: int):\n super().contractDetailsEnd(reqId)\n req = Request.find(reqId)\n if req.condition.acquire():\n req.condition.notifyAll()\n req.condition.release()\n\n def nextValidId(self, orderId: int):\n super().nextValidId(orderId)\n self._next_valid_id = orderId\n\n @alarm(target=\"尝试连接\", freq=Timedelta(minutes=10))\n def try_connect(self):\n # 先清理掉无效的连接\n if self.cli.connState == EClient.CONNECTED:\n self.cli.disconnect()\n self.cli.connect(self.host, self.port, self.client_id)\n if self.cli.connState == EClient.CONNECTED and self.cli.reader.is_alive():\n threading.Thread(name=\"ib_msg_consumer\", target=self.cli.run).start()\n # 等待客户端初始化成功\n time.sleep(3)\n # 重新订阅\n for callback in self.client_status_callbacks:\n callback.re_connect()\n else:\n raise RuntimeError(\"重新连接失败\")\n\n def __init__(self, host, port, client_id):\n super().__init__()\n cli = EClient(self)\n self.cli = cli\n self.host = host\n self.port = port\n self.client_id = client_id\n self.account_subscriber = None\n self.tick_subscriber = None\n self.market_data_subscriber: EWrapper = None\n self._next_valid_id = None\n self.code_contract_map = {}\n self.client_status_callbacks: List[ClientStatusCallback] = []\n self.try_connect()\n\n # 启动ping线程,如果与服务器的连接丢失,则会尝试重新连接\n def ping():\n # retry_count = 0\n while True:\n try:\n if cli.connState != EClient.CONNECTED or not cli.reader.is_alive():\n logging.info(\"尝试重新连接\")\n self.try_connect()\n except:\n import traceback\n logging.error(\"{}\".format(traceback.format_exc()))\n\n time.sleep(10)\n\n threading.Thread(name=\"ib_ping\", target=ping).start()\n\n def req_history_data(self, code: str, end_date_time: Timestamp, duration_str, bar_size, what_to_show,\n use_rth: int, format_date: int, keep_up_to_date, char_options) -> List[BarData]:\n req = Request.new_request()\n contract = self.code_to_contract(code)\n self.cli.reqHistoricalData(req.req_id, contract,\n end_date_time.strftime(\"%Y%m%d %H:%M:%S\") if end_date_time else \"\",\n duration_str, bar_size,\n what_to_show, use_rth, format_date, keep_up_to_date, char_options)\n if req.condition.acquire():\n req.condition.wait(20)\n if not req.resp:\n self.cli.cancelHistoricalData(req.req_id)\n raise RuntimeError(\"获取数据超时或者没有获取到数据\")\n resp = req.resp\n # 清理数据\n Request.clear(req.req_id)\n # 返回排好序的数据\n return sorted(resp, key=lambda bar: bar.date)\n\n def _req_history_ticks(self, code: str, start: Timestamp, end: Timestamp, nums: int, what_to_show: str,\n use_rth: int,\n ignore_size: bool, misc_options) -> List[HistoricalTickLast]:\n req = Request.new_request()\n contract = self.code_to_contract(code)\n self.cli.reqHistoricalTicks(req.req_id, contract,\n start.strftime(\"%Y%m%d %H:%M:%S\") if start is not None else \"\",\n end.strftime(\"%Y%m%d %H:%M:%S\"), nums, what_to_show,\n use_rth, ignore_size, misc_options)\n if req.condition.acquire():\n req.condition.wait(10)\n if not req.resp:\n raise RuntimeError(\"获取数据超时或者没有获取到数据\")\n resp = req.resp\n Request.clear(req.req_id)\n return resp\n\n def req_min_bar(self, command: HistoryDataQueryCommand) -> Mapping[str, List[BarData]]:\n code_to_bars = {}\n for code in command.codes:\n bars: List[BarData] = []\n batch_end = command.end\n while True:\n batch_bars = self.req_history_data(code, end_date_time=batch_end, duration_str=\"86400 S\",\n bar_size='1 min',\n what_to_show='TRADES', use_rth=1, format_date=1,\n keep_up_to_date=False,\n char_options=None)\n bars.extend(batch_bars[::-1])\n if command.start and command.end:\n # 检查start时间\n if Timestamp(bars[-1].date, tz='Asia/Shanghai') <= command.start:\n break\n else:\n # 检查window\n if len(bars) >= command.window:\n break\n batch_end = Timestamp(bars[-1].date, tz='Asia/Shanghai')\n code_to_bars[code] = bars\n return code_to_bars\n\n def req_tick(self, command: HistoryDataQueryCommand) -> Mapping[str, List[HistoricalTickLast]]:\n\n ticks_map = {}\n for code in command.codes:\n ticks: List[HistoricalTickLast] = []\n batch_end = command.end\n while True:\n # 如果指定了开始时间,则每次获取1000条,否则使用command里面定义的window\n window = 1000 if command.start else command.window\n batch_ticks = self._req_history_ticks(code, None, batch_end, nums=window,\n what_to_show='TRADES',\n use_rth=1, ignore_size=False, misc_options=None)\n ticks.extend(batch_ticks)\n if command.start and command.end:\n if Timestamp(batch_ticks[0].time, unit='s', tz='Asia/Shanghai') <= command.start:\n break\n else:\n if len(ticks) >= command.window:\n break\n batch_end = Timestamp(batch_ticks[0].time, unit='s', tz='Asia/Shanghai')\n ticks_map[code] = ticks\n\n return ticks_map\n\n def code_to_contract(self, code) -> Contract:\n if code in self.code_contract_map:\n return self.code_contract_map[code]\n contract = Contract()\n ss = code.split(\"_\")\n contract.symbol = ss[0]\n contract.secType = ss[1]\n contract.currency = ss[2]\n contract.exchange = ss[3]\n if len(ss) > 4:\n contract.lastTradeDateOrContractMonth = ss[4]\n contracts: List[Contract] = self.query_contract(contract)\n if len(contracts) != 1:\n raise RuntimeError(\"code不能唯一确定一个合约\")\n self.code_contract_map[code] = contracts[0]\n return contracts[0]\n\n def contract_to_code(self, contract: Contract):\n return \"_\".join([contract.symbol, contract.secType, contract.currency, contract.exchange])\n\n def query_contract(self, contract):\n req = Request.new_request()\n self.cli.reqContractDetails(req.req_id, contract)\n\n if req.condition.acquire():\n req.condition.wait(20)\n if not req.resp:\n raise RuntimeError(\"没有获取到数据\")\n resp = req.resp\n # 清理数据\n Request.clear(req.req_id)\n return resp\n\n def placeOrder(self, ib_order_id, contract, order):\n self.cli.placeOrder(ib_order_id, contract, order)\n\n def next_valid_id(self):\n if not self._next_valid_id:\n raise RuntimeError(\"no next_valid_id\")\n self._next_valid_id += 1\n return self._next_valid_id\n\n @classmethod\n def find_client(cls, host, port, client_id):\n key = \"{}_{}_{}\".format(host, port, client_id)\n if key in cls.clients_map:\n return cls.clients_map[key]\n return None\n\n @classmethod\n def registry(cls, host, port, client_id, cli: IBClient):\n key = \"{}_{}_{}\".format(host, port, client_id)\n cls.clients_map[key] = cli\n\n def sub(self, account_subscriber: EWrapper = None, tick_subscriber: EWrapper = None,\n market_data_subscriber: EWrapper = None):\n if account_subscriber:\n self.account_subscriber = account_subscriber\n if tick_subscriber:\n self.tick_subscriber = tick_subscriber\n if market_data_subscriber:\n self.market_data_subscriber = market_data_subscriber\n\n def register_client_status_callback(self, callback: ClientStatusCallback):\n if callback not in self.client_status_callbacks:\n self.client_status_callbacks.append(callback)\n\n\nclass IBCurrentPrice(RTTimeSeriesType, EWrapper, ClientStatusCallback):\n \"\"\"\n IB实时数据\n \"\"\"\n\n def re_connect(self):\n if len(self.sub_codes) > 0:\n logging.info(\"重新订阅实时数据,codes:{}\".format(self.sub_codes))\n self.do_sub(self.sub_codes)\n\n def tickPrice(self, reqId: TickerId, tickType: TickType, price: float, attrib: TickAttrib):\n req = Request.find(reqId)\n code = req.code\n if tickType == 1:\n # bid price\n if code in self.current_price_map:\n self.current_price_map[code] = self.current_price_map[code].with_new_bid_price(price)\n else:\n cp: CurrentPrice = self._default_cp(code)\n cp = cp.with_new_bid_price(price)\n self.current_price_map[code] = cp\n elif tickType == 2:\n # ask price\n if code in self.current_price_map:\n self.current_price_map[code] = self.current_price_map[code].with_new_ask_price(price)\n else:\n self.current_price_map[code] = self._default_cp(code).with_new_ask_price(price)\n\n for sub in self.sub_map[code]:\n sub.on_data(self.current_price_map[code])\n\n def _default_cp(self, code):\n now = Timestamp.now(tz='Asia/Shanghai')\n return CurrentPrice(self.name(), now, code,\n {\"price\": None, 'ask_price': None, 'ask_size': None, 'bid_price': None, 'bid_size': None})\n\n def tickSize(self, reqId: TickerId, tickType: TickType, size: int):\n code = Request.find(reqId).code\n values = {\n 'tick_type': tickType,\n 'value': size,\n }\n if tickType == 0:\n # bid size\n if code in self.current_price_map:\n self.current_price_map[code] = self.current_price_map[code].with_new_bid_size(size)\n else:\n self.current_price_map[code] = self._default_cp(code).with_new_bid_size(size)\n elif tickType == 3:\n # ask size\n if code in self.current_price_map:\n self.current_price_map[code] = self.current_price_map[code].with_new_ask_size(size)\n else:\n self.current_price_map[code] = self._default_cp(code).with_new_ask_size(size)\n for sub in self.sub_map[code]:\n sub.on_data(self.current_price_map[code])\n\n def tickString(self, reqId: TickerId, tickType: TickType, value: str):\n code = Request.find(reqId).code\n if tickType == 48:\n # 45表示RTVolume\n values = value.split(';')\n if len(values[0]) > 0:\n # 这个时间我们会丢弃,使用接收到数据的时间作为当前价格的时间戳\n # 因为收取到买卖价格的时候是没有时间戳的\n price_time = Timestamp(int(values[2]), unit='ms', tz='Asia/Shanghai')\n now = Timestamp.now(tz='Asia/Shanghai')\n try:\n self._time_check(price_time, now)\n except:\n pass\n new_price = float(values[0])\n if code in self.current_price_map:\n self.current_price_map[code] = self.current_price_map[code].with_new_price(new_price)\n else:\n self.current_price_map[code] = self._default_cp(code).with_new_price(new_price)\n\n for sub in self.sub_map[code]:\n sub.on_data(self.current_price_map[code])\n\n @alarm(level=AlarmLevel.ERROR, target=\"数据延迟检查\", freq=Timedelta(minutes=1),\n escape_params=[EscapeParam(index=0, key='self')])\n def _time_check(self, server_time: Timestamp, receive_time: Timestamp):\n if (receive_time - server_time) > Timedelta(seconds=5):\n raise RuntimeError(\"接收的数据延迟过高\")\n\n def name(self) -> str:\n return 'ibCurrentPrice'\n\n def current_price(self, codes) -> Mapping[str, CurrentPrice]:\n ret = {}\n for code in codes:\n if code in self.current_price_map:\n ret[code] = self.current_price_map[code]\n return ret\n\n def do_sub(self, codes: List[str]):\n for code in codes:\n contract: Contract = self.client.code_to_contract(code)\n req = Request.new_request()\n self.client.cli.reqMktData(req.req_id, contract, '233', False, False, None)\n self.code_to_req[code] = req\n req.code = code\n\n def do_unsub(self, codes):\n for code in codes:\n req_id = self.code_to_req[code].req_id\n self.client.cli.cancelMktData(req_id)\n Request.clear(req_id)\n\n def __init__(self):\n super().__init__()\n\n # cli = IBClient.find_client(host, port, client_id)\n # if not cli:\n # cli = IBClient(host, port, client_id)\n # IBClient.registry(host, port, client_id, cli)\n global client\n client.sub(market_data_subscriber=self)\n client.register_client_status_callback(self)\n self.client = client\n self.code_to_req: Mapping[str, Request] = {}\n self.current_price_map: Mapping[str, CurrentPrice] = {}\n\n\nclass IBAdjustedDailyBar(BarHistoryTimeSeriesType):\n\n def name(self) -> str:\n return \"ibAdjustedDailyBar\"\n\n def should_cache(self):\n return False\n\n def load_history_data(self, command: HistoryDataQueryCommand) -> List[TSData]:\n if not command.calendar:\n raise RuntimeError(\"need calendar\")\n start = command.start\n if not start:\n weeks = math.ceil(command.window / 5)\n start = command.end - Timedelta(weeks=weeks)\n\n ys = math.ceil((Timestamp.now(tz='Asia/Shanghai') - start).days / 365)\n total_ts_data: List[TSData] = []\n\n for code in command.codes:\n # 返回的bar的日期,是收盘时刻对应的UTC标准时间的日期部分\n bars: List[BarData] = self.client.req_history_data(code, None, \"{} Y\".format(ys), \"1 day\",\n \"ADJUSTED_LAST\", 1, 1, False, None)\n for bar in bars:\n dt = Timestamp(bar.date, tz='UTC')\n visible_time = command.calendar.next_close(dt).tz_convert('Asia/Shanghai')\n start_time = (command.calendar.previous_open(visible_time) - Timedelta(minutes=1)).tz_convert(\n 'Asia/Shanghai')\n provider_data = {\"start_time\": start_time, \"open\": bar.open, \"high\": bar.high, \"low\": bar.low,\n \"close\": bar.close, \"volume\": bar.volume}\n ts_data = TSData(self.name(), visible_time, code, self.parse(provider_data))\n total_ts_data.append(ts_data)\n\n return total_ts_data\n\n def load_assets(self) -> List[Asset]:\n raise RuntimeError(\"not supported\")\n\n def columns(self) -> List[Column]:\n columns = [Column(\"start_time\", Timestamp, None, None, None), Column(\"open\", float, None, None, None),\n Column(\"high\", float, None, None, None), Column(\"low\", float, None, None, None),\n Column(\"close\", float, None, None, None), Column(\"volume\", int, None, None, None)]\n return columns\n\n def __init__(self):\n super().__init__(current_price_change_start_offset=Timedelta(days=1),\n current_price_change_end_offset=Timedelta(days=365 * 2))\n\n # cli = IBClient.find_client(host, port, client_id)\n # if not cli:\n # cli = IBClient(host, port, client_id)\n # IBClient.registry(host, port, client_id, cli)\n global client\n self.client = client\n self.cp_mem_cache: Mapping[str, DataFrame] = {}\n\n\nclass IBMinBar(BarHistoryTimeSeriesType):\n\n def __init__(self):\n super().__init__(current_price_change_start_offset=Timedelta(minutes=5),\n current_price_change_end_offset=Timedelta(minutes=1440 * 10))\n # cli = IBClient.find_client(host, port, client_id)\n # if not cli:\n # cli = IBClient(host, port, client_id)\n # IBClient.registry(host, port, client_id, cli)\n global client\n self.client = client\n\n def name(self) -> str:\n return \"ibMinBar\"\n\n def load_history_data(self, command: HistoryDataQueryCommand) -> List[TSData]:\n code_to_bars: Mapping[str, List[BarData]] = self.client.req_min_bar(command)\n all_ts_datas = []\n one_minute = Timedelta(minutes=1)\n for code in code_to_bars.keys():\n\n for bar in code_to_bars.get(code):\n dt = Timestamp(bar.date, tz='Asia/Shanghai')\n visible_time = dt + one_minute\n provider_data = {\"date\": dt, \"open\": bar.open, \"high\": bar.high, \"low\": bar.low, \"close\": bar.close,\n \"volume\": bar.volume}\n ts_data = TSData(self.name(), visible_time, code, self.parse(provider_data))\n all_ts_datas.append(ts_data)\n\n return all_ts_datas\n\n def load_assets(self) -> List[Asset]:\n pass\n\n def columns(self) -> List[Column]:\n columns = [Column(\"date\", Timestamp, None, None, None), Column(\"open\", float, None, None, None),\n Column(\"high\", float, None, None, None), Column(\"low\", float, None, None, None),\n Column(\"close\", float, None, None, None), Column(\"volume\", int, None, None, None)]\n return columns\n","sub_path":"se2/infras/ib.py","file_name":"ib.py","file_ext":"py","file_size_in_byte":25129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"653438145","text":"from app import app\nfrom flask import render_template, flash, redirect, url_for\nfrom app.forms import LoginForm\nfrom flask_login import current_user, login_user, login_required\nfrom app.models import User, Result\nfrom flask_login import logout_user\nfrom flask import request\nfrom werkzeug.urls import url_parse\n\nfrom app import db\nfrom app.forms import RegistrationForm, AnswerForm\n\n@app.route('/')\ndef welcome():\n return render_template(\"welcome.html\")\n\n@app.route('/home')\ndef home():\n return render_template(\"Home.html\")\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('Invalid username or password, please try again')\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('home')\n return redirect(next_page)\n return render_template('login.html', title='Sign In', form=form,)\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(username=form.username.data, email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you are now a registered user!')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n \n@app.route('/learn')\ndef learn():\n return render_template(\"learn.html\")\n\n@app.route('/assessment_home')\ndef assessment_home():\n return render_template(\"assessment_home.html\")\n\n@app.route('/assessment', methods=['GET', 'POST'])\ndef assessment():\n form = AnswerForm()\n if form.validate_on_submit():\n score,correct = getmark(form)\n result = Result(user_id=current_user.get_id(),mark=score)\n db.session.add(result)\n db.session.commit()\n return redirect(url_for('feedback', score = score, correct = correct))\n return render_template(\"assessment.html\", form=form)\n\n@app.route('/table')\n@login_required\ndef table():\n results = Result.query.filter_by(user_id=current_user.get_id()).all()\n return render_template(\"table.html\", results=results)\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('home'))\n\n@app.route('/feedback?')\ndef feedback(score,correct):\n return render_template(\"feedback.html\", score = score, correct = correct)\n\ndef getmark(form):\n score = 0\n correct = []\n if form.q1.data == 'nu':\n score += 10\n correct.append(1)\n if form.q2.data == 'nume':\n score += 10\n correct.append(2)\n if form.q3.data == 'ネ':\n score += 10\n correct.append(3)\n if form.q4.data == 'を':\n score += 10\n correct.append(4)\n if form.q5.data == 'ga ka':\n score += 10\n correct.append(5)\n if form.q6.data == 'ノ':\n score += 10\n correct.append(6)\n if form.q7.data == 'へ':\n score += 10\n correct.append(7)\n if form.q8.data == 'た':\n score += 10\n correct.append(8)\n if form.q9.data == 'ぽ':\n score += 10\n correct.append(9)\n if form.q10.data == 'ん':\n score += 10\n correct.append(10)\n return score, correct\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"443912945","text":"#!/usr/bin/python\n\nimport math\n\ndef format_label(value, tick):\n\tif tick < 0.00001:\n\t\tfmtstr = \"%02d:%02d:%09.6f\"\n\telif tick < 0.0001:\n\t\tfmtstr = \"%02d:%02d:%08.5f\"\n\telif tick < 0.001:\n\t\tfmtstr = \"%02d:%02d:%07.4f\"\n\telif tick < 0.01:\n\t\tfmtstr = \"%02d:%02d:%06.3f\"\n\telif tick < 0.1:\n\t\tfmtstr = \"%02d:%02d:%05.2f\"\n\telif tick < 1:\n\t\tfmtstr = \"%02d:%02d:%04.1f\"\n\telse:\n\t\tfmtstr = \"%02d:%02d:%02.0f\"\n\thour = int(value) / 3600\n\tmin = int(value - hour * 3600) / 60\n\tsec = value - hour * 3600 - min * 60\n\treturn fmtstr % (hour, min, sec)\n# end of format_label\n\nTIME_SCALE_OPTIONS = [\n\t(5, 5, 0.000001), \n\t(10, 5, 0.000002), \n\t(5, 5, 0.00001), \n\t(10, 5, 0.0001), \n\t(10, 5, 0.0002), \n\t(5, 5, 0.0001), \n\t(10, 5, 0.0001), \n\t(10, 5, 0.002), \n\t(5, 5, 0.001), \n\t(10, 5, 0.001), \n\t(10, 5, 0.002), \n\t(5, 5, 0.01), \n\t(10, 5, 0.01), \n\t(10, 5, 0.02), \n\t(5, 5, 0.1), \n\t(10, 5, 0.1), \n\t(10, 5, 0.2), \n\t(5, 5, 1), \n\t(10, 5, 1), \n\t(10, 5, 2), \n\t(3, 3, 10), \n\t(10, 5, 6), \n\t(10, 5, 12), \n\t(5, 5, 60), \n\t(10, 5, 60), \n\t(10, 5, 120), \n\t(3, 3, 600), \n\t(6, 3, 600), \n\t(12, 6, 600), \n\t(4, 4, 1800), \n\t(8, 4, 1800), \n\t(8, 4, 3600), \n\t(12, 6, 3600), \n]\n\nclass Metrics:\n\tdef __init__(self, layout, width=200, height=74, rate=8000, \n\t\t\t\tchannels=1, draw_in=0, draw_out=8000*60):\n\t\tself.layout = layout\n\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.draw_in = draw_in\n\t\tself.draw_out = draw_out\n\n\t\tself.rate = rate\n\t\tself.channels = channels\n\n\t\tself.ch_stride = -1\n\t\tself.ticks = {}\n\t\tself.grids = []\n\t\tself.labels = []\n\t\tself.x_array = []\n\t\tself.timetick = []\n\t\tself.timetag = []\n\n\t\tself.update_volume_grid()\n\t\tself.update_time_grid()\n\n\tdef update(self, width, height, rate, channels, draw_in, draw_out):\n\t\tif height != self.height or channels != self.channels:\n\t\t\tself.height = height\n\t\t\tself.channels = channels\n\t\t\tself.update_volume_grid()\n\n\t\tif (width != self.width or rate != self.rate or\n\t\t\t\tdraw_in != self.draw_in or draw_out != self.draw_out):\n\t\t\tself.width = width\n\t\t\tself.rate = rate\n\t\t\tself.draw_in = draw_in\n\t\t\tself.draw_out = draw_out\n\t\t\tself.update_time_grid()\n\n\tdef update_volume_grid(self):\n\t\tself.ch_stride = (self.height + 2.0) / self.channels\n\t\th = round(self.ch_stride - 2) - 1\n\t\tstart = 0\n\t\tif h >= 400:\n\t\t\ttick_stride, grid_stride, label_stride = 1, 5, 10\n\t\telif h >= 200:\n\t\t\ttick_stride, grid_stride, label_stride = 2, 10, 20\n\t\telif h >= 80:\n\t\t\ttick_stride, grid_stride, label_stride = 10, 50, 50\n\t\telif h >= 40:\n\t\t\ttick_stride, grid_stride, label_stride = 10, 50, 100\n\t\telse:\n\t\t\ttick_stride, grid_stride, label_stride = 20, 100, 100\n\t\t\tstart = 100\n\t\tself.ticks = dict([(x, int(round(h * x / 200))) \n\t\t\t\tfor x in range(0, 201, tick_stride)])\n\t\tself.grids = [x for x in range(0, 201, grid_stride)]\n\t\tself.labels = [x for x in range(start, 201, label_stride)]\n\n\tdef update_time_grid(self):\n\t\tlayout = self.layout\n\t\tpixel_per_sec = (self.width - 1.) * self.rate / \\\n\t\t\t\t(self.draw_out - self.draw_in)\n\t\ttime_scale = {}\n\t\ti = 0\n\t\twhile not time_scale:\n\t\t\tif i < len(TIME_SCALE_OPTIONS) - 1:\n\t\t\t\tmajor, minor, tick = TIME_SCALE_OPTIONS[i]\n\t\t\t\ti += 1\n\t\t\telse:\n\t\t\t\tmajor = 12\n\t\t\t\tminor = 6\n\t\t\t\ttick *= 2\n\t\t\tpixel_per_grid = pixel_per_sec * minor * tick\n\t\t\tif pixel_per_grid < 25:\n\t\t\t\tcontinue\n\t\t\tpixel_per_label = pixel_per_sec * major * tick\n\t\t\tmax_label = format_label(self.draw_out * self.rate, tick)\n\t\t\tlayout.set_text(max_label)\n\t\t\tlabel_width, label_height = layout.get_pixel_size()\n\t\t\tif label_width + 10 > pixel_per_label:\n\t\t\t\tcontinue\n\t\t\ttime_scale = {\"major\": major, \"minor\": minor, \"tick\": tick}\n\t\t\tbreak\n\t\tsec_per_grid = time_scale[\"tick\"] * time_scale[\"minor\"]\n\t\tsec_draw_in = self.draw_in * 1.0 / self.rate\n\t\tsec_draw_out = self.draw_out * 1.0 / self.rate\n\t\tsec_start = math.floor(sec_draw_in / sec_per_grid) * sec_per_grid\n\t\tsec_curr = sec_start\n\t\tcounter = 0\n\t\tself.x_array = []\n\t\tself.timetick = []\n\t\tself.timetag = []\n\t\twhile sec_curr <= sec_draw_out:\n\t\t\tx = int(round((sec_curr - sec_draw_in) * pixel_per_sec))\n\t\t\tif counter % time_scale[\"major\"] == 0:\n\t\t\t\tself.x_array.append(x)\n\t\t\t\tself.timetick.append((x, 5))\n\t\t\t\tself.timetag.append((x, format_label(sec_curr, time_scale[\"tick\"])))\n\t\t\telif counter % time_scale[\"minor\"] == 0:\n\t\t\t\tself.x_array.append(x)\n\t\t\t\tself.timetick.append((x, 3))\n\t\t\telse:\n\t\t\t\tself.timetick.append((x, 1))\n\t\t\tcounter += 1\n\t\t\t#sec_curr = sec_start + sec_per_grid * counter\n\t\t\tsec_curr = sec_start + time_scale[\"tick\"] * counter\n\n\tdef get_x_array(self):\n\t\treturn self.x_array\n\n\tdef get_timetick(self):\n\t\treturn self.timetick\n\n\tdef get_timetag(self):\n\t\treturn self.timetag\n\n\tdef get_channel_base_y(self, ch):\n\t\treturn int(self.ch_stride * ch)\n\n\tdef get_channel_height(self):\n\t\treturn int(round(self.ch_stride - 2))\n\n\tdef get_ticks(self):\n\t\tresult = []\n\t\tfor i in sorted(self.ticks):\n\t\t\ty = self.ticks[i]\n\t\t\tif i in self.labels:\n\t\t\t\tresult.append((y, 7))\n\t\t\telif i in self.grids:\n\t\t\t\tresult.append((y, 3))\n\t\t\telse:\n\t\t\t\tresult.append((y, 1))\n\t\treturn result\n\n\tdef get_grid_lines(self):\n\t\treturn [self.ticks[i] for i in self.grids]\n\n\tdef get_labels(self):\n\t\tresult = []\n\t\tfor i in self.labels[:-1]:\n\t\t\tresult.append((self.ticks[i], \"%.1f\" % (1-i/100.)))\n\t\treturn result\n\n\tdef get_center(self):\n\t\treturn self.ticks[100]\n\n# end of class Metrics\n\n# end of $URL$\n\n","sub_path":"Metrics.py","file_name":"Metrics.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"4616029","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n \n \n if not root:\n return None\n self.helper(root, 0)\n return root\n \n \n \n def helper(self, root:TreeNode, total: int)-> int:\n \n if not root.right and not root.left:\n root.val += total\n return root.val\n \n if root.right:\n total = self.helper(root.right, total)\n \n root.val += total\n total = root.val\n \n if root.left:\n total = self.helper(root.left, total)\n \n return total","sub_path":"binary-search-tree-to-greater-sum-tree/binary-search-tree-to-greater-sum-tree.py","file_name":"binary-search-tree-to-greater-sum-tree.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"158890349","text":"from .cost import Cost\n\nimport numpy as np\nimport json\n\n\nclass ParticleVectorNLocalConvolution4Network(object):\n\n def __init__(self, particle_input=None, cost=\"mse\", regularizer=None):\n self.layers = []\n self.cost_name = cost\n self.cost_function = Cost.get(cost)\n self.cost_d_function = Cost.get_d(cost)\n self.lock_built = False\n self.regularizer = regularizer\n self.particle_input = particle_input\n\n def append(self, layer):\n \"\"\"\n Appends a layer to the network\n\n :param layer:\n :return:\n \"\"\"\n self.layers.append(layer)\n\n def build(self):\n \"\"\"\n Handle networks layer dimensions checks, other possible initializations\n\n Release build lock\n\n :return:\n \"\"\"\n # TODO\n\n self.lock_built = True\n\n def predict_single(self, data_X):\n \"\"\"\n Same as predict, but only one sample\n \"\"\"\n return self.predict(data_X.reshape((1, len(data_X))))\n\n def predict(self, data_X):\n \"\"\"\n Pass given input through network to compute the output prediction\n\n :param data_X:\n :return:\n \"\"\"\n a, r = self.particle_input.feed_forward(data_X)\n for layer in self.layers:\n a, r = layer.feed_forward(a, r)\n return a\n\n def feed_to_layer(self, data_X, end_layer=0):\n \"\"\"\n Feed data forward until given end layer. Return the resulting activation\n\n :param data_X: input data\n :param end_layer: the index of the ending layer\n :return: resulting activation at end layer\n \"\"\"\n if len(self.layers) <= end_layer < 0:\n return None\n\n a, r = self.particle_input.feed_forward(data_X)\n for l, layer in enumerate(self.layers):\n a, r = layer.feed_forward(a, r)\n if l == end_layer:\n return a\n\n return None\n\n def cost(self, data_X, data_Y):\n \"\"\"\n Compute the cost for all input data corresponding to expected output\n\n :param data_X:\n :param data_Y:\n :return:\n \"\"\"\n c = self.cost_function(data_Y, self.predict(data_X))\n\n if self.regularizer is not None:\n c += self.regularizer.cost(self.particle_input, self.layers)\n\n return c\n\n def cost_gradient_thread(self, data_XYt):\n \"\"\"\n Wrapper for multithreaded call\n :param data_XY:\n :return:\n \"\"\"\n return self.cost_gradient(data_XYt[0], data_XYt[1], thread_scale=data_XYt[2])\n\n def cost_gradient(self, data_X, data_Y, thread_scale=1):\n \"\"\"\n Computes the gradient of the cost with respect to each weight and bias in the network\n\n :param data_X:\n :param data_Y:\n :return:\n \"\"\"\n\n # Output gradients\n dc_db = []\n dc_dr = [[np.zeros(self.particle_input.output_size) for _ in range(self.particle_input.nr)]]\n dc_dn = [[np.zeros(self.particle_input.output_size) for _ in range(self.particle_input.nv)]]\n dc_dm = [[np.zeros(self.particle_input.output_size) for _ in range(self.particle_input.nw)]]\n # Initialize\n for l, layer in enumerate(self.layers):\n dc_db.append(np.zeros(layer.b.shape))\n dc_dr.append([np.zeros(layer.output_size) for _ in range(self.particle_input.nr)])\n dc_dn.append([np.zeros(layer.output_size) for _ in range(self.particle_input.nv)])\n dc_dm.append([np.zeros(layer.output_size) for _ in range(self.particle_input.nw)])\n\n sigma_Z = []\n A_scaled, _ = self.particle_input.feed_forward(data_X)\n A = [A_scaled] # Note: A has one more element than sigma_Z\n prev_layer_rr = self.particle_input.get_rxyz()\n for l, layer in enumerate(self.layers):\n z = layer.compute_z(A[l], prev_layer_rr, apply_input_noise=(l == 0))\n a = layer.compute_a(z, apply_dropout=True)\n A.append(a)\n sigma_Z.append(layer.compute_da(z, apply_dropout=True))\n prev_layer_rr = layer.get_rxyz()\n\n delta_L = self.cost_d_function(data_Y, A[-1], sigma_Z[-1])\n\n # IMPORTANT:\n # For threaded calls, we need to divide the cost gradient by the number threads to account for the mean being\n # taken in the cost function. When data is split, the mean is off by a factor of the number of threads.\n if thread_scale > 1:\n delta_L /= thread_scale\n\n # For each piece of data\n for di, data in enumerate(data_X):\n dc_db[-1] += delta_L[di]\n\n # Reshape\n for r in range(self.particle_input.nr):\n self.particle_input.positions[r] = self.particle_input.positions[r].reshape((self.particle_input.output_size, 1))\n for v in range(self.particle_input.nv):\n self.particle_input.nvectors[v] = self.particle_input.nvectors[v].reshape((self.particle_input.output_size, 1))\n for w in range(self.particle_input.nw):\n self.particle_input.nwectors[w] = self.particle_input.nwectors[w].reshape((self.particle_input.output_size, 1))\n for layer in self.layers:\n for r in range(layer.nr):\n layer.positions[r] = layer.positions[r].reshape((layer.output_size, 1))\n for v in range(layer.nv):\n layer.nvectors[v] = layer.nvectors[v].reshape((layer.output_size, 1))\n for w in range(layer.nw):\n layer.nwectors[w] = layer.nwectors[w].reshape((layer.output_size, 1))\n\n if layer.apply_convolution:\n layer.positions_cache = layer.positions_cache.reshape((layer.nr, len(layer.positions_cache[0]), 1))\n layer.nvectors_cache = layer.nvectors_cache.reshape((layer.nv, len(layer.nvectors_cache[0]), 1))\n layer.nwectors_cache = layer.nwectors_cache.reshape((layer.nw, len(layer.nwectors_cache[0]), 1))\n\n l = -1\n layer = self.layers[l]\n prev_layer = self.particle_input if -(l-1) > len(self.layers) else self.layers[l-1]\n\n Al = A[l-1]\n Al_trans = Al.transpose()\n trans_delta_L = delta_L.transpose()\n trans_sigma_Z = []\n for sz in sigma_Z:\n trans_sigma_Z.append(np.asarray(sz).transpose())\n\n next_delta = np.zeros((len(prev_layer.positions[0]), len(data_X)))\n\n # Position gradient\n for j in range(layer.output_size):\n trans_delta_L_j = trans_delta_L[j]\n trans_sigma_Z_l = trans_sigma_Z[l-1] if -(l-1) <= len(self.layers) else np.ones((prev_layer.output_size, len(data_X)))\n\n d2 = None\n lpos = None\n if layer.apply_convolution:\n d2 = np.zeros((len(prev_layer.positions[0]), len(data_X))) # this is amazing stuff! numpy is the best!\n lpos = layer.positions_cache\n\n else:\n d2 = np.zeros_like(prev_layer.positions[0])\n lpos = layer.positions\n\n dr = []\n for r in range(layer.nr):\n dtmp = prev_layer.positions[r] - lpos[r][j]\n d2 += dtmp ** 2\n dr.append(dtmp)\n\n d = np.sqrt(d2)\n dot = 0.0\n for v in range(layer.nv):\n dot += prev_layer.nvectors[v] * layer.nwectors[v][j]\n exp_dij = layer.potential(d, layer.zeta) * dot\n\n # Next delta\n next_delta += trans_delta_L_j * exp_dij * trans_sigma_Z_l\n atj = Al_trans * trans_delta_L_j\n dq = exp_dij * atj\n\n # Position gradient\n tmp = -dot * atj * layer.d_potential(d, layer.zeta) / d\n for r in range(layer.nr):\n tr = dr[r] * tmp\n dc_dr[l][r][j] += np.sum(tr)\n dc_dr[l - 1][r] -= np.sum(tr, axis=1)\n\n # Vector gradient\n tmp = dq / dot\n for v in range(layer.nv):\n tv = tmp * prev_layer.nvectors[v]\n dc_dm[l][v][j] += np.sum(tv)\n tv = tmp * layer.nwectors[v][j]\n dc_dn[l - 1][v] += np.sum(tv, axis=1)\n\n l = -1\n while -l < len(self.layers):\n l -= 1\n # Gradient computation\n layer = self.layers[l]\n prev_layer = self.particle_input if -(l-1) > len(self.layers) else self.layers[l-1]\n\n Al = A[l-1]\n Al_trans = Al.transpose()\n\n this_delta = next_delta\n if layer.apply_convolution:\n this_delta = this_delta.reshape((layer.output_size, layer.n_convolution, -1))\n # Bias gradient\n trans_delta = np.sum(this_delta, axis=1).transpose()\n for di, data in enumerate(data_X):\n dc_db[l] += trans_delta[di]\n else:\n # Bias gradient\n trans_delta = this_delta.transpose()\n for di, data in enumerate(data_X):\n dc_db[l] += trans_delta[di]\n\n if prev_layer.apply_convolution:\n next_delta = np.zeros((len(prev_layer.positions_cache[0]), len(data_X)))\n trans_sigma_Z_l = trans_sigma_Z[l - 1] if -(l - 1) <= len(self.layers) else np.ones((len(prev_layer.positions_cache[0]), len(data_X)))\n\n else:\n next_delta = np.zeros((prev_layer.output_size, len(data_X)))\n trans_sigma_Z_l = trans_sigma_Z[l-1] if -(l-1) <= len(self.layers) else np.ones((prev_layer.output_size, len(data_X)))\n\n prev_n_out = prev_layer.output_size * prev_layer.n_convolution\n lpos = None\n lvec = None\n if layer.apply_convolution:\n # use the non-flattened caches\n lpos = layer.positions_cache2.reshape((layer.nr, layer.output_size, layer.n_convolution, len(data_X), 1)) # use the max pool contributor position\n lvec = layer.nwectors_cache.reshape((layer.nw, layer.output_size, layer.n_convolution, 1))\n else:\n lpos = layer.positions\n lvec = layer.nwectors\n\n # Position gradient\n for j in range(layer.output_size):\n this_delta_j = this_delta[j]\n d2 = None\n dot = 0.0\n dr = []\n\n if layer.apply_convolution:\n if prev_layer.apply_convolution:\n d2 = np.zeros((layer.n_convolution, len(data_X), prev_n_out, 1))\n dr = np.zeros((layer.n_convolution, layer.nr, len(data_X), prev_n_out, 1))\n for c in range(layer.n_convolution):\n for a in range(len(data_X)):\n for r in range(layer.nr):\n dtmp = prev_layer.positions_cache[r] - lpos[r][j][c][a]\n d2[c][a] += dtmp ** 2\n dr[c][r][a] += dtmp\n for w in range(layer.nw):\n dot += prev_layer.nvectors_cache[w] * lvec[w][j][c]\n d = np.sqrt(d2)\n\n else:\n d2 = np.zeros((layer.n_convolution, len(data_X), prev_layer.output_size, 1))\n dr = np.zeros((layer.n_convolution, layer.nr, len(data_X), prev_layer.output_size, 1))\n for c in range(layer.n_convolution):\n for a in range(len(data_X)):\n for r in range(layer.nr):\n dtmp = prev_layer.positions[r] - lpos[r][j][c][a]\n d2[c][a] += dtmp ** 2\n dr[c][r][a] += dtmp\n for w in range(layer.nw):\n dot += prev_layer.nvectors[w] * lvec[w][j][c]\n d = np.sqrt(d2)\n\n else:\n if prev_layer.apply_convolution:\n d2 = np.zeros_like(prev_layer.positions_cache[0])\n for r in range(layer.nr):\n dtmp = prev_layer.positions_cache[r] - lpos[r][j]\n d2 += dtmp ** 2\n dr.append(dtmp)\n d = np.sqrt(d2)\n for w in range(layer.nw):\n dot += prev_layer.nvectors_cache[w] * lvec[w][j]\n else:\n d2 = np.zeros_like(prev_layer.positions[0])\n for r in range(layer.nr):\n dtmp = prev_layer.positions[r] - lpos[r][j]\n d2 += dtmp ** 2\n dr.append(dtmp)\n d = np.sqrt(d2)\n for w in range(layer.nw):\n dot += prev_layer.nvectors[w] * lvec[w][j]\n\n exp_dij = layer.potential(d, layer.zeta) * dot\n\n # Next delta\n if layer.apply_convolution:\n # Loop through each j-th convolution\n next_delta = next_delta.transpose()\n sigma_Z_l = trans_sigma_Z_l.transpose()\n\n ld_pot = (layer.d_potential(d, layer.zeta) / d).reshape((layer.n_convolution, len(data_X), prev_n_out))\n exp_dij = exp_dij.reshape((layer.n_convolution, len(data_X), prev_n_out))\n this_delta_j = this_delta_j.reshape((layer.n_convolution, len(data_X), 1))\n dr = dr.reshape((layer.n_convolution, layer.nr, len(data_X), prev_n_out))\n\n if prev_layer.apply_convolution:\n for c in range(layer.n_convolution):\n # todo: still not sure why the average works here... max pooling dependent input??\n next_delta += this_delta_j[c] * exp_dij[c] * sigma_Z_l / (layer.n_convolution * len(data_X))\n\n atj = Al * this_delta_j[c]\n dq = (exp_dij[c] * atj).reshape((len(data_X), prev_n_out, 1))\n v_tmp = (dq / dot).reshape((len(data_X), prev_n_out))\n\n jcdot = 0.0\n for w in range(layer.nw):\n jcdot += prev_layer.nvectors_cache[w] * lvec[w][j][c]\n p_tmp = -jcdot.flatten() * atj * ld_pot[c] # only the dot for this j-th conv?\n\n for r in range(layer.nr):\n tr = dr[c][r] * p_tmp\n dc_dr[l][r][j] += np.sum(tr)\n dc_dr[l - 1][r] -= np.sum(np.sum(tr, axis=0).reshape((len(prev_layer.positions[0]), -1)), axis=1)\n\n for w in range(layer.nw):\n tv = v_tmp * prev_layer.nvectors_cache[w].flatten()\n dc_dm[l][w][j] += np.sum(tv)\n tv = v_tmp * layer.nwectors[w][j]\n dc_dn[l - 1][w] += np.sum(np.sum(tv, axis=0).reshape((len(prev_layer.nvectors[0]), -1)), axis=1)\n\n else:\n for c in range(layer.n_convolution):\n next_delta += this_delta_j[c] * exp_dij[c] * sigma_Z_l\n atj = Al * this_delta_j[c]\n dq = (exp_dij[c] * atj).reshape((len(data_X), prev_n_out, 1))\n v_tmp = (dq / dot).reshape((len(data_X), prev_n_out))\n\n jcdot = 0.0\n for w in range(layer.nw):\n jcdot += prev_layer.nvectors[w] * lvec[w][j][c]\n p_tmp = -jcdot.flatten() * atj * ld_pot[c] # only the dot for this j-th conv?\n\n for r in range(layer.nr):\n tr = dr[c][r] * p_tmp\n dc_dr[l][r][j] += np.sum(tr)\n dc_dr[l - 1][r] -= np.sum(tr, axis=0)\n\n for w in range(layer.nw):\n tv = v_tmp * prev_layer.nvectors[w].flatten()\n dc_dm[l][w][j] += np.sum(tv)\n tv = v_tmp * layer.nwectors[w][j]\n dc_dn[l - 1][w] += np.sum(tv, axis=0)\n\n next_delta = next_delta.transpose()\n\n else:\n exp_dij = exp_dij.reshape((-1, 1))\n\n next_delta += this_delta_j * exp_dij * trans_sigma_Z_l\n atj = Al_trans * this_delta_j\n dq = exp_dij * atj\n\n p_tmp = -dot * atj * layer.d_potential(d, layer.zeta) / d\n v_tmp = dq / dot\n\n if prev_layer.apply_convolution:\n for r in range(layer.nr):\n tr = dr[r] * p_tmp\n dc_dr[l][r][j] += np.sum(tr)\n dc_dr[l - 1][r] -= np.sum(np.sum(tr, axis=1).reshape((len(prev_layer.positions[0]), -1)), axis=1)\n\n for w in range(layer.nw):\n tv = v_tmp * prev_layer.nvectors_cache[w]\n dc_dm[l][w][j] += np.sum(tv)\n tv = v_tmp * layer.nwectors[w][j]\n dc_dn[l - 1][w] += np.sum(np.sum(tv, axis=1).reshape((len(prev_layer.nvectors[0]), -1)), axis=1)\n else:\n for r in range(layer.nr):\n tr = dr[r] * p_tmp\n dc_dr[l][r][j] += np.sum(tr)\n dc_dr[l - 1][r] -= np.sum(tr, axis=1)\n\n for w in range(layer.nw):\n tv = v_tmp * prev_layer.nvectors[w]\n dc_dm[l][w][j] += np.sum(tv)\n tv = v_tmp * layer.nwectors[w][j]\n dc_dn[l - 1][w] += np.sum(tv, axis=1)\n\n # Restore shapes\n for r in range(self.particle_input.nr):\n self.particle_input.positions[r] = self.particle_input.positions[r].reshape((self.particle_input.output_size, ))\n for v in range(self.particle_input.nv):\n self.particle_input.nvectors[v] = self.particle_input.nvectors[v].reshape((self.particle_input.output_size, ))\n for w in range(self.particle_input.nw):\n self.particle_input.nwectors[w] = self.particle_input.nwectors[w].reshape((self.particle_input.output_size, ))\n for layer in self.layers:\n for r in range(layer.nr):\n layer.positions[r] = layer.positions[r].reshape((layer.output_size, ))\n for v in range(layer.nv):\n layer.nvectors[v] = layer.nvectors[v].reshape((layer.output_size, ))\n for w in range(layer.nw):\n layer.nwectors[w] = layer.nwectors[w].reshape((layer.output_size, ))\n\n if layer.apply_convolution:\n layer.positions_cache = layer.positions_cache.reshape((layer.nr, len(layer.positions_cache[0]), ))\n layer.nvectors_cache = layer.nvectors_cache.reshape((layer.nv, len(layer.nvectors_cache[0]), ))\n layer.nwectors_cache = layer.nwectors_cache.reshape((layer.nw, len(layer.nwectors_cache[0]), ))\n\n # Regularizer\n if self.regularizer is not None:\n # dc_dr = self.regularizer.cost_gradient(self.particle_input, self.layers, dc_dr)\n dc_dn, dc_db = self.regularizer.cost_gradient(self.particle_input, self.layers, dc_dn, dc_db)\n\n return dc_db, dc_dr, dc_dn, dc_dm\n\n def fit(self, data_X, data_Y, optimizer):\n \"\"\"\n Run the optimizer for specified number of epochs\n\n :param data_X:\n :param data_Y:\n :return:\n \"\"\"\n\n return optimizer.optimize(self, data_X, data_Y)\n\n def write_to_json(self, file=None):\n \"\"\"\n Write network data to file in JSON format\n :param file: a file open for writing\n :return:\n \"\"\"\n pass\n","sub_path":"src/calrissian/particle_vector_n_network_local_conv4.py","file_name":"particle_vector_n_network_local_conv4.py","file_ext":"py","file_size_in_byte":20170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"89247426","text":"from songs import Songs\nfrom playlists import Playlists\nfrom wordpool import WordPool\nfrom settings import Settings\nimport functions as func\n\nimport os\n\n\ndef search_and_save():\n pls = Playlists()\n # 获得前50项歌单\n pls.get_playlists(st)\n\n if not os.path.exists('res/' + st.csv_fname + '.csv'):\n # 递归下载歌单\n pls.recur_playlists(st)\n\n\ndef single_playlist():\n if not os.path.exists('res/' + st.csv_fname + '.csv'):\n # 新建一个歌单类\n s = Songs()\n s.get_plist(st.playlist_url, st)\n s.get_lyric()\n func.songs_to_csv(s.songs, st)\n\n\nif __name__ == \"__main__\":\n st = Settings()\n # 新建一个词池\n w = WordPool()\n\n if st.toggle == True:\n search_and_save()\n else:\n single_playlist()\n w.get_wordpool(st)\n if st.word_rank:\n w.word_freq(st)\n w.generate_wordcloud()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"8773119","text":"#!/usr/bin/env python\n\"\"\"Run the fastqc pipeline.\n\nThis runs FastQC on a number of files.\n\nIt requires a YAML configuration file with parameters for FastQC (output directory, etc.)\nIt also requires a samples file that has at least a column named 'sample' and 'filename'.\n\n\"\"\"\n\nimport csv\nimport sys\nimport os\nimport argparse\nimport subprocess\n\nfrom ruffus import *\nimport yaml\n\nfrom ccrngspy.tasks import FastQC\nfrom ccrngspy import utils\n\nfrom ccrngspy.pipeline import fastqc_helpers\n\nlogger = utils.make_local_logger(\"FastQC logging\", level=\"debug\", color=\"green\")\n\nparser = argparse.ArgumentParser(description=\"Run fastqc on files.\")\n\nparser.add_argument(\"--print_only\", dest=\"print_only\", action=\"store_true\", default=False,\n help=\"Don't run the pipeline, just print what will be run.\")\n\nparser.add_argument('--config_file', dest=\"config_file\", type=str,\n help=\"A YAML configuration file for pipeline.\")\n\nparser.add_argument('--sample_file', dest=\"sample_file\", type=str,\n help=\"A YAML configuration file for pipeline.\")\n\n# add options for the fastqc task\nparser = FastQC.FastQC().argparse(parser)\n\n# Parse the options\nopts = parser.parse_args()\n\n# Load the bootstrap config file\nwith open(opts.config_file, 'r') as configfile:\n config = yaml.load(configfile)\n\n# Load the samples tab-separated file\nwith open(opts.sample_file, 'r') as samplefile:\n reader = csv.DictReader(samplefile, delimiter=\"\\t\")\n samples = list(reader)\n\n\ntest_task_params = make_fastqc_param_list(samples=samples, config=config)\n\n#----------------------------------------------\n# begin tasks here\n#----------------------------------------------\n\n@files(test_task_params)\ndef run_fastqc(input, output, params=None):\n \"\"\"Set up and run the fastqc program.\n \n \"\"\"\n\n fastqc_task = FastQC.FastQC(input_files=[input], output_directory=config['fastqc_params']['output_dir'])\n fastqc_task.run_fastqc()\n\n # post task, touch output file!\n of = file(output, mode=\"w\")\n of.close()\n\nif opts.print_only:\n pipeline_printout(sys.stdout, [run_fastqc])\nelse:\n pipeline_run([run_fastqc], multiprocess=5)\n\n","sub_path":"scripts/fastqc.py","file_name":"fastqc.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"549918924","text":"from time import sleep\n\n\n\n\n#TEST\nclass s_IA():\n\tdef __init__(self):\n\t\tself.gyro_z_offset = 0\n\t\tself.gyro_pos = 0 # 0N 90E 180S 270O\n\t\tself.flag = 0# <180 0 >180 1 \n\t\tself.tour = 5\n\n\t\tself.coef = 1.5\n\n\tdef go(self, robot):\n\t\tself.gyro_z_offset = robot.input_sensor.gyro(2, robot)\n\t\tself.gyro_pos += self.tour*360 + self.gyro_z_offset + 180\n\t\twhile True:\n\t\t\t\n\t\t\ttry:\n\t\t\t\trobot.input_sensor.scan_moy(4, robot)\n\t\t\t\tif robot.input_sensor.ultra_son_moy[1] > 30:\n\t\t\t\t\tself.aller_droite(robot)\n\t\t\t\t\tself.aller_tout_droit(robot, 1/(self.coef) + 0.5, 1)\n\t\t\t\telif robot.input_sensor.ultra_son_moy[0] > 30:\n\t\t\t\t\tself.aller_tout_droit(robot, 0.1, 0)\n\t\t\t\telif robot.input_sensor.ultra_son_moy[3] > 30:\n\t\t\t\t\tself.aller_gauche(robot)\n\t\t\t\t\tself.aller_tout_droit(robot, 1/(self.coef) + 0.5, 1)\n\t\t\t\telse:\n\t\t\t\t\tself.aller_gauche(robot)\n\t\t\t\t\tself.aller_gauche(robot)\n\n\t\t\texcept:\n\t\t\t\tprint(\"ERREUR ! go IA\")\n\t\t\t\trobot.output.traitement_input(robot, [1, 0, 0, 0, 0])\n\n\tdef aller_gauche(self, robot):\n\t\tprint(\"IA : GAUCHE \")\n\t\trobot.output.traitement_input(robot, [1, 10*(self.coef), -20*(self.coef), 1, 0])\n\t\twhile self.pi360(robot) < self.gyro_pos + 90:\n\t\t\tsleep(0.03)\n\t\t\tprint(\"gauche cur:%d obj:%d gyro_pos:%d\" %(self.pi360(robot), self.gyro_pos + 90, self.gyro_pos))\n\t\tself.gyro_pos += 90\n\n\tdef aller_droite(self, robot):\n\t\tprint(\"IA : DROITE \")\n\t\trobot.output.traitement_input(robot, [1, 10*(self.coef), 20*(self.coef), 1, 0])\n\t\twhile self.pi360(robot) > self.gyro_pos - 90:\n\t\t\tsleep(0.03)\n\t\t\tprint(\"droite cur:%d obj:%d gyro_pos:%d\" %(self.pi360(robot), self.gyro_pos - 90, self.gyro_pos))\n\t\tself.gyro_pos -= 90\n\n\tdef aller_tout_droit(self, robot, temps, assmur):#assmur 0 oui, 1 non\n\t\tprint(\"IA : T.D. \")\n\t\ttemps_int = int(temps / 0.1)\n\t\tfor i in range(temps_int):\n\n\t\t\trobot.input_sensor.scan_moy(1, robot)\n\t\t\trobot.output.traitement_input(robot, [1, 30*(self.coef), self.pi360(robot)-self.gyro_pos, assmur, 0])\n\t\t\tsleep(0.1)\n\t\t\n\t\t#robot.output.traitement_input(robot, [1, 0, 0, 0, 0])\n\n\tdef pi360(self, robot):\n\t\tgy = robot.input_sensor.gyro(3, robot) + 180 - self.gyro_z_offset\n\t\tgy_mod = (gy+self.tour*360)%360\n\t\tif(gy_mod > 90 and gy_mod < 270):\n\t\t\tif(gy_mod > 180 and self.flag == 0):\n\t\t\t\tself.flag = 1\n\t\t\telif(gy_mod < 180 and self.flag == 1):\n\t\t\t\tself.flag = 0\n\n\t\tif(gy_mod < 90 and self.flag == 1):\n\t\t\tself.flag = 0\n\t\t\tself.tour += 1\n\t\telif(gy_mod > 270 and self.flag == 0):\n\t\t\tself.flag = 1\n\t\t\tself.tour -= 1\n\n\t\treturn robot.input_sensor.gyro(3, robot) + 180 - self.gyro_z_offset + self.tour*360\n\n\n\n\n\n\n\n\n\n\n\n\n#CLASS\n#class s_Carte():\n#\tdef __init__(self):\n#\t\tself.intersection = [s_Intersection()]\n#\t\tself.intersection[0].dir_set([2, 0, 3, 0], [None, None, None, None])\n#\t\tself.inter_last\n#\t\tself.eg\n#\n#\tdef new_intersection(self):\n#\t\tself.\n#\n#\n#class s_Intersection():\n#\tdef __init__(self):\n#\t\tself.dir = []\n#\t\tself.pointer = []\n#\t\tself.sens = []\n#\n#\n#\n#\tdef dir_set(self, dir_tab, dir_pointer):\n#\t\t#0 mur, 1 chemain connu, 2 chemin inconnu, 3 sortie\n#\n#\t\tself.dir = [dir_tab[0], dir_tab[1], dir_tab[2], dir_tab[3]]\n#\t\tself.pointer = [dir_pointer[0], dir_pointer[1], dir_pointer[2], dir_pointer[3]]\n#\t\t#0,1,2,3 -> sens connu; -1 inconnu; -2 sortie\n#\t\tself.sens = [-1, -1, -1, -1]\n#\t\treturn 0","sub_path":"nationales/codeBrouillon/PYTHON/IA.py","file_name":"IA.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"566247040","text":"from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom document import Document\nfrom string import punctuation\nfrom demoji import findall\nimport stemmer\n\n\nclass Parse:\n\n numeric_counter = 0\n\n months = {\"jan\": \"1\", \"january\": \"1\", \"feb\": \"2\", \"february\": \"2\", \"mar\": \"3\", \"march\": \"3\", \"apr\": \"4\",\n \"april\": \"4\", \"may\": \"5\", \"jun\": \"6\", \"june\": \"6\", \"jul\": \"7\", \"july\": \"7\", \"aug\": \"8\", \"august\": \"8\",\n \"sep\": \"9\", \"september\": \"9\", \"oct\": \"10\", \"october\": \"10\", \"nov\": \"11\", \"november\": \"11\", \"dec\": \"12\",\n \"december\": \"12\"}\n\n days = {\"first\": \"1\", \"1st\": \"1\", \"second\": \"2\", \"2nd\": \"2\", \"third\": \"3\", \"fourth\": \"4\", \"4th\": \"4\", \"fifth\": \"5\",\n \"5th\": \"5\", \"sixth\": \"6\", \"6th\": \"6\", \"seventh\": \"7\", \"7th\": \"7\", \"eighth\": \"8\", \"8th\": \"8\", \"ninth\": \"9\",\n \"9th\": \"9\", \"tenth\": \"10\", \"10th\": \"10\", \"eleventh\": \"11\", \"11th\": \"11\", \"twelfth\": \"12\", \"12th\": \"12\",\n \"thirteenth\": \"13\", \"13th\": \"13\", \"fourteenth\": \"14\", \"14th\": \"14\", \"fifteenth\": \"15\", \"15th\": \"15\",\n \"sixteenth\": \"16\", \"16th\": \"16\", \"seventeenth\": \"17\", \"17th\": \"17\", \"eighteenth\": \"18\", \"18th\": \"18\",\n \"nineteenth\": \"19\", \"19th\": \"19\", \"twentieth\": \"20\", \"twenty\": \"20\", \"20th\": \"20\", \"twenty-first\": \"21\",\n \"21tst\": \"21\", \"22nd\": \"22\", \"twenty-second\": \"22\", \"23rd\": \"23\", \"twenty-third\": \"23\", \"24th\": \"24\",\n \"twenty-fourth\": \"24\", \"25th\": \"25\", \"twenty-fifth\": \"25\", \"26th\": \"26\", \"twenty-sixth\": \"26\",\n \"27th\": \"27\", \"twenty-seventh\": \"27\", \"28th\": \"28\", \"twenty-eighth\": \"28\", \"twenty-ninth\": \"29\",\n \"29th\": \"29\", \"30th\": \"30\", \"thirty\": \"30\", \"31st\": \"31\", \"thirty-first\": \"31\"}\n\n def __init__(self):\n self.stop_words = stopwords.words('english')\n self.stop_words.extend([\"rt\", \"n't\", \"'re\", \"gon\", \"na\", \"covid\", \"coronavirus\", \"covid-19\"])\n self.punctuation_to_remove = punctuation.replace('#', '').replace('@', '').replace('%', '').replace('$', '')\n self.symbols = \"<>:\\\"/\\\\|!?*~.'`-_()^,+=;\"\n self.token_stemmer = stemmer.Stemmer()\n\n def get_valid_url(self, url_col):\n \"\"\"\n :param url_col: \"urls\" column or \"retweet_urls\" or \"quote_urls\" columns\n :return: pure valid url or empty string if no valid url was present. format - {\"\":\"return_value\"}\n \"\"\"\n\n if url_col != \"{}\":\n trans_table = url_col.maketrans(\"\\\"\", \" \")\n urls = url_col.translate(trans_table)\n urls = urls.split()\n if len(urls) == 5:\n return urls[3]\n return \"\"\n\n def parse_hashtag_underscore(self, text_tokens, i):\n \"\"\"\n this function deals with hashtags of the form #stay_at_home\n :param text_tokens: list of tokens that is changed according to the given rules\n :param i: the index of the \"#\" token\n \"\"\"\n token = text_tokens[i + 1]\n del text_tokens[i + 1]\n joined_hashtag = '#'\n insertion_index = 0\n num_inserted = 0\n splited_tokens = token.split(\"_\")\n for j in range(len(splited_tokens)):\n if splited_tokens[j] != \"\":\n text_tokens.insert(i + 1 + insertion_index, splited_tokens[j].lower())\n insertion_index += 1\n num_inserted += 1\n joined_hashtag += splited_tokens[j]\n text_tokens[i] = joined_hashtag\n\n def parse_hashtag_camel_case(self, text_tokens, i):\n \"\"\"\n this function parses hashtags of the the type #StayAtHome #stayAtHome\n :param text_tokens: list of tokens that is changed\n :param i: \"#\" index\n \"\"\"\n token = text_tokens[i + 1]\n del text_tokens[i + 1]\n j = 0\n joined_hashtag = '#'\n from_index = 0\n insertion_index = 0\n while j < len(token):\n if token[j].isupper() and j != 0:\n text_tokens.insert(i + 1 + insertion_index, token[from_index:j].lower())\n joined_hashtag += token[from_index:j].lower()\n from_index = j\n insertion_index += 1\n j += 1\n if token[from_index:len(token)] != '':\n joined_hashtag += token[from_index:len(token)].lower()\n text_tokens.insert(i + 1 + insertion_index, token[from_index:len(token)].lower())\n text_tokens[i] = joined_hashtag\n\n def parse_hashtag_upper_case(self, text_tokens, i):\n\n \"\"\"\n this function parses hashtags of the the type #COVID19 #NJ\n :param text_tokens: list of tokens that is changed\n :param i: \"#\" index\n \"\"\"\n joined_hashtag = '#'\n joined_hashtag += text_tokens[i+1].lower()\n text_tokens[i] = joined_hashtag # \"#covid19\"\n\n def parse_hashtag(self, text_tokens, i):\n \"\"\"\n this function calls to parse underscore or parse camel case respectively\n :param - i the index of\n :return - return False if the hashtag contained not ascii values else return True\n \"\"\"\n\n if len(text_tokens) > i + 1 and not text_tokens[i+1].isascii():\n del text_tokens[i] # deleting ashtag\n del text_tokens[i] # deleting not ascii symbol\n return False\n\n # parsing snake case\n if len(text_tokens) > i + 1 and text_tokens[i + 1].count('_') > 0:\n self.parse_hashtag_underscore(text_tokens, i)\n\n elif len(text_tokens) > i+1 and text_tokens[i+1].isupper():\n self.parse_hashtag_upper_case(text_tokens, i)\n\n # parsing pascal and camel cases\n elif len(text_tokens) > i + 1:\n self.parse_hashtag_camel_case(text_tokens, i)\n return True\n\n def parse_tagging(self, text_tokens, i):\n \"\"\"\n this function appends @ and name that our tokenizer separates\n :param text_tokens: list of tokens\n :param i: index of '@'\n :return:\n \"\"\"\n if len(text_tokens) > i + 1:\n text_tokens[i] += text_tokens[i + 1]\n del text_tokens[i + 1]\n\n def parse_url(self, text_tokens, i):\n \"\"\"\n this function parses url according to the rules.\n :param text_tokens: list of tokens\n :param i: index of \"https\"\n \"\"\"\n del text_tokens[i] # removing 'https or http'\n if len(text_tokens) > i and text_tokens[i] == \":\":\n if text_tokens[i] == ':':\n del text_tokens[i] # removing ':'\n\n link_token = text_tokens[i]\n\n tokens_in_url = link_token.split(\"/\")\n del text_tokens[i]\n\n token_index = 0\n while token_index < len(tokens_in_url):\n if tokens_in_url[token_index] == \"t.co\":\n break\n if tokens_in_url[token_index] != \"twitter.com\" and tokens_in_url[token_index] != \"\":\n text_tokens.insert(i + token_index, tokens_in_url[token_index].lstrip(\"w.\"))\n token_index += 1\n\n def is_float(self, number):\n\n \"\"\"\n Verify if a string can be converted to float\n :param number - string to be converted\n :return Boolean - can be converted or not\n \"\"\"\n\n try:\n float(number.replace(\",\", \"\"))\n if number.lower() != \"infinity\":\n return True\n except ValueError:\n return False\n\n def parse_numeric_values(self, text_tokens, index):\n\n \"\"\"\n Parse numeric tokens according to specified rules.\n Any number in the thousands, millions and billions will be abbreviated to #K, #M and #B respectively\n Any number signifying percentage will be shown as #%\n Fractions of the format #/# will stay the same\n :param text_tokens: list of tokens to be parsed\n :param index: index of currently parsed token\n \"\"\"\n\n self.numeric_counter += 1\n token = text_tokens[index]\n numeric_token = float(token.replace(\",\", \"\"))\n\n # format large numbers\n # any number in the thousands, millions and billions will be abbreviated to #K, #M and #B respectively\n if 1000 <= numeric_token < 1000000:\n formatted_token = \"{num:.3f}\".format(num=(numeric_token / 1000)).rstrip(\"0\").rstrip(\".\") + \"K\"\n text_tokens[index] = formatted_token\n elif len(text_tokens) > index + 1 and text_tokens[index + 1].lower() == \"thousand\":\n formatted_token = str(numeric_token).rstrip(\"0\").rstrip(\".\") + \"K\"\n text_tokens[index] = formatted_token\n del text_tokens[index + 1]\n elif 1000000 <= numeric_token < 1000000000:\n formatted_token = \"{num:.3f}\".format(num=numeric_token / 1000000).rstrip(\"0\").rstrip(\".\") + \"M\"\n text_tokens[index] = formatted_token\n elif len(text_tokens) > index + 1 and text_tokens[index + 1].lower() == \"million\":\n formatted_token = str(numeric_token).rstrip(\"0\").rstrip(\".\") + \"M\"\n text_tokens[index] = formatted_token\n del text_tokens[index + 1]\n elif 1000000000 <= numeric_token:\n formatted_token = \"{num:.3f}\".format(num=numeric_token / 1000000000).rstrip(\"0\").rstrip(\".\") + \"B\"\n text_tokens[index] = formatted_token\n elif len(text_tokens) > index + 1 and text_tokens[index + 1].lower() == \"billion\":\n formatted_token = str(numeric_token).rstrip(\"0\").rstrip(\".\") + \"B\"\n text_tokens[index] = formatted_token\n del text_tokens[index + 1]\n\n # parse percentage\n # any number signifying percentage will be shown as #%\n if len(text_tokens) > index + 1:\n lower_case_next_token = text_tokens[index + 1].lower()\n if lower_case_next_token == \"%\" or lower_case_next_token == \"percent\" \\\n or lower_case_next_token == \"percentage\":\n formatted_token = str(numeric_token).rstrip(\"0\").rstrip(\".\") + \"%\"\n text_tokens[index] = formatted_token\n del text_tokens[index + 1]\n\n def parse_date(self, text_tokens, index):\n \"\"\"\n this function calls the appropriate function to parse a date.\n :param text_tokens: list of tokens\n :param index: the index of the month or the index of the 'MM/DD/YY' token\n :return: - reduction of the index as a result of deletion of previous tokens\n in some cases such as '15th of July' we want to delete '15' and 'of' and insert '7~15'\n in this cases we should bring the index back\n \"\"\"\n\n if text_tokens[index].lower() in self.months:\n return self.parse_date_according_to_month(text_tokens, index)\n\n if text_tokens[index].count(\"/\") == 2:\n self.parse_date_slash(text_tokens, index)\n return 0\n\n def parse_date_according_to_month(self, text_tokens, index):\n \"\"\"\n parsing date of format '15 of Jun' or '15th of June' etc. to 'MM~DD' format\n :return - reduction of the index as a result of deletion of previous tokens\n in some cases such as '15th of July' we want to delete '15' and 'of' and insert '7~15'\n in this cases we should bring the index back\n \"\"\"\n\n if len(text_tokens) > index + 1 and text_tokens[index].lower() in self.months:\n if text_tokens[index + 1] in self.days: # July 15th\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + self.days.get(text_tokens[index + 1])\n del text_tokens[index + 1]\n elif text_tokens[index + 1].isnumeric(): # July 15\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + str(int(text_tokens[index + 1]))\n del text_tokens[index + 1]\n elif index - 1 >= 0:\n if text_tokens[index - 1] in self.days: # 15th July\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + self.days.get(text_tokens[index - 1])\n del text_tokens[index - 1]\n return 1\n elif text_tokens[index - 1].isnumeric(): # 15 July\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + str(int(text_tokens[index - 1]))\n del text_tokens[index - 1]\n return 1\n elif text_tokens[index - 1] == \"of\" and index - 2 >= 0 \\\n and text_tokens[index - 2] in self.days: # 15th of July\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + self.days.get(text_tokens[index - 2])\n del text_tokens[index - 1] # delete for\n del text_tokens[index - 1] # delete 15th\n return 2\n\n elif text_tokens[index - 1] == \"of\" and text_tokens[index - 2].isnumeric(): # 15 of july\n text_tokens[index] = self.months.get(text_tokens[index].lower()) + \\\n \"~\" + str(int(text_tokens[index - 2]))\n del text_tokens[index - 1] # delete for\n del text_tokens[index - 1] # delete 15\n return 2\n return 0\n\n def parse_date_slash(self, text_tokens, index):\n \"\"\"\n parse date with slash 'MM/DD/YY'\n to ['MM~DD', 'YY']\n @:param - index of the 'MM/DD/YY' token\n \"\"\"\n\n splitted_date = text_tokens[index].split(\"/\")\n if len(splitted_date) == 3 and splitted_date[0].isnumeric() and splitted_date[1].isnumeric() \\\n and splitted_date[2].isnumeric():\n if int(splitted_date[0]) in range(0, 13) and int(splitted_date[1]) in range(0, 32):\n text_tokens[index] = str(int(splitted_date[0])) + \"~\" + str(int(splitted_date[1]))\n text_tokens.insert(index + 1, splitted_date[2])\n\n def parse_fraction(self, text_tokens, index):\n \"\"\"\n this function parses fraction according to given rules ['35', '3/4'] - > ['35 3/4']\n :param text_tokens:\n :param index:\n :return:\n \"\"\"\n\n splited_fruction = text_tokens[index].split(\"/\")\n if index - 1 > 0 and text_tokens[index - 1].isnumeric() and \\\n splited_fruction[0].isnumeric and splited_fruction[1].isnumeric():\n text_tokens[index - 1] = text_tokens[index - 1] + \" \" + text_tokens[index]\n del text_tokens[index]\n return True\n else:\n return False\n\n def parse_entities(self, text_tokens, index, entities):\n\n \"\"\"\n Identify possible entities in the document.\n A possible entity is any sequence of tokens starting with a capital letter\n :param text_tokens: list of tokens to be parsed\n :param index: index of current parsed token\n :param entities: dictionary of possible entities\n \"\"\"\n current_token = text_tokens[index]\n entity = \"\"\n\n # find a sequence of terms with capital letters\n while index + 1 < len(text_tokens) and current_token[0].isupper():\n entity += current_token + \" \"\n index += 1\n current_token = text_tokens[index]\n entity.rstrip(\" \")\n\n # add new possible entity to dictionary\n if entity != \"\":\n if entity not in entities:\n entities[entity] = 1\n else:\n entities[entity] += 1\n\n def parse_capital_letters(self, tokenized_text, term_dict):\n\n \"\"\"\n Parses token according to capital letters rule.\n Ensures a uniform appearance of tokens - if a token only appears in capital form - record as upper case\n Else, record in lower case\n :param tokenized_text - list, list of parsed tokens\n :param term_dict - dictionary, record uniform token appearance according to rule in currently parsed document\n \"\"\"\n\n index = 0\n while index < len(tokenized_text):\n\n token = tokenized_text[index]\n\n if token != '':\n\n # save token as upper case\n # save token as lower and upper case\n formatted_token_lower = token.lower()\n formatted_token_upper = token.upper()\n\n # Add token to term dictionary\n # In the dictionary keep the term_frequency\n # term_frequency - how many times the term appeared in the document\n # key indicates if term is capital or lower case\n\n # Check if first letter is a capital letter\n if token[0].isupper():\n # check in which form the token appears in dictionary and update it accordingly\n if formatted_token_upper not in term_dict and formatted_token_lower not in term_dict:\n term_dict[formatted_token_upper] = 1\n elif formatted_token_upper in term_dict:\n term_dict[formatted_token_upper] += 1\n else: # formatted_token_lower in capitals\n term_dict[formatted_token_lower] += 1\n\n # If current term is lower case change key to lower case\n else:\n # check in which form the token appears in dictionary and update it accordingly\n if formatted_token_upper not in term_dict and formatted_token_lower not in term_dict:\n term_dict[formatted_token_lower] = 1\n elif formatted_token_upper in term_dict: # replace format of token from upper case to lower case\n term_dict[formatted_token_lower] = term_dict[formatted_token_upper] + 1\n term_dict.pop(formatted_token_upper, None) # remove upper case form from the dictionary\n else: # formatted_token_lower in capitals\n term_dict[formatted_token_lower] += 1\n\n index += 1\n\n def parse_sentence(self, text, entities=None, stemming=False):\n\n \"\"\"\n This function tokenize, remove stop words and apply lower case for every word within the text\n :param text: string - text to be parsed\n :param entities: dictionary - record possible entities in currently parsed document\n :param stemming: boolean variable True - with stemming, False - without stemming\n :return: list of parsed tokens\n \"\"\"\n\n text_tokens = word_tokenize(text)\n\n index = 0\n while index < len(text_tokens):\n\n if text_tokens[index].lower() not in self.stop_words\\\n and text_tokens[index] not in self.punctuation_to_remove\\\n and text_tokens[index].isascii():\n\n # removing unnecessary symbols\n text_tokens[index] = text_tokens[index].rstrip(self.symbols).lstrip(self.symbols)\n if text_tokens[index] == \"\":\n del text_tokens[index]\n continue\n\n if text_tokens[index] == '#':\n if not self.parse_hashtag(text_tokens, index):\n continue\n elif text_tokens[index] == '@':\n self.parse_tagging(text_tokens, index)\n elif text_tokens[index] == 'https' or text_tokens[index] == 'http':\n self.parse_url(text_tokens, index)\n continue\n\n # parse numeric values\n elif self.is_float(text_tokens[index]):\n self.parse_numeric_values(text_tokens, index)\n\n # parse dates\n elif text_tokens[index].lower() in self.months or \\\n text_tokens[index].count(\"/\") == 2:\n index -= self.parse_date(text_tokens, index)\n\n # parse fractions\n elif text_tokens[index].count(\"/\") == 1:\n if self.parse_fraction(text_tokens, index):\n continue\n\n # parse entities\n # entity is every sequence of tokens starting with a capital letter \\\n # and appearing at least twice in the entire corpus\n if index + 1 < len(text_tokens) and text_tokens[index][0].isupper() \\\n and text_tokens[index + 1][0].isupper():\n self.parse_entities(text_tokens, index, entities)\n\n # apply stemmer if stemming is True\n if stemming and len(text_tokens[index]) > 0 and text_tokens[index][0] not in \"@#\":\n after_stemming = self.token_stemmer.stem_term(text_tokens[index])\n if after_stemming != '':\n text_tokens[index] = after_stemming\n\n if len(text_tokens[index]) == 1:\n del text_tokens[index]\n continue\n\n index += 1\n else:\n if not text_tokens[index].isascii():\n # token is not ascii\n valid_token = ''\n for char in text_tokens[index]:\n if char.isascii():\n valid_token += char # separate valid token from the ascii symbol appended to him\n else:\n # parsing emoji\n emoji = [*findall(char).values()] # unpack single emoji token and put in list\n if len(emoji) > 0 and emoji[0] not in text_tokens:\n text_tokens.append(emoji[0])\n if len(emoji[0].split()) > 1:\n # add to text tokens emojis such as: 'smiling face', 'smiling', 'face'\n for emoji_token in emoji[0].split():\n text_tokens.append(emoji_token)\n\n if valid_token != '': # append the valid toke\n text_tokens[index] = valid_token\n\n # apply stemmer if stemming is True\n if stemming and valid_token[0] not in \"@#\":\n after_stemming = self.token_stemmer.stem_term(valid_token)\n if after_stemming != '':\n text_tokens[index] = after_stemming\n\n else:\n del text_tokens[index] # not ascii symbols that we want to delete\n else:\n del text_tokens[index] # RT or punctuation that is in ascii\n\n if index > 0 and text_tokens[index - 1] == '':\n del text_tokens[index]\n\n return text_tokens\n\n def prep_url(self, url):\n \"\"\"\n remove unnecessary signs from urls and not meaningful digits and letters\n \"\"\"\n trans_table = url.maketrans(\"\\\\/|=<>.?%-:_\", \" \")\n parsed_url = url.translate(trans_table)\n parsed_url_tokens = parsed_url.split()\n token_index = 0\n while token_index < len(parsed_url_tokens):\n if parsed_url_tokens[token_index].isdigit() \\\n or len(parsed_url_tokens[token_index]) == 1 \\\n or parsed_url_tokens[token_index] in [\"www\", \"co\", \"com\", \"twitter\", \"status\", \"web\", \"https\",\n \"http\"]:\n parsed_url_tokens.remove(parsed_url_tokens[token_index])\n continue\n token_index += 1\n\n return \" \".join(parsed_url_tokens)\n\n def remove_shortened_urls(self, full_text):\n try:\n full_text.index(\"https\")\n return \" \".join(filter(lambda splitted: splitted[:5] != 'https', full_text.split()))\n except ValueError:\n return full_text\n\n def parse_doc(self, doc_as_list, stemming=False):\n \"\"\"\n This function takes a tweet document as list and break it into different fields\n :param stemming: Whether to performe stemming or not\n :type stemming: bool\n :param doc_as_list: list re-presenting the tweet.\n :return: Document object with corresponding fields.\n \"\"\"\n\n url = \"\"\n retweet_url = \"\"\n quote_url = \"\"\n tweet_id = doc_as_list[0]\n tweet_date = doc_as_list[1]\n full_text = doc_as_list[2]\n full_text = self.remove_shortened_urls(full_text)\n if doc_as_list[3] and doc_as_list[3] != \"\":\n url = self.get_valid_url(doc_as_list[3])\n url = self.prep_url(url)\n retweet_text = doc_as_list[5]\n if doc_as_list[6] and doc_as_list[6] != \"\":\n retweet_url = self.get_valid_url(doc_as_list[6])\n retweet_url = self.prep_url(retweet_url)\n quote_text = doc_as_list[8]\n if quote_text:\n quote_text = self.remove_shortened_urls(quote_text)\n else:\n quote_text = \"\"\n if doc_as_list[9] and doc_as_list[9] != \"\":\n quote_url = self.get_valid_url(doc_as_list[9])\n quote_url = self.prep_url(quote_url)\n term_dict = {}\n\n # dictionary for holding possible entities\n entities = dict()\n\n pre_processed_text = full_text + \" \" + quote_text + \" \" + url + \" \" + retweet_url + \" \" + quote_url\n tokenized_text = self.parse_sentence(pre_processed_text, entities, stemming)\n\n doc_length = len(tokenized_text) # after text operations.\n\n # parse token by lower or upper case rule\n # parsing will build the term dictionary in a uniform upper/lower form and calculate the term frequency\n self.parse_capital_letters(tokenized_text, term_dict)\n\n max_tf = 0\n for tf in term_dict.values():\n if tf > max_tf:\n max_tf = tf\n\n unique_term_number = len(term_dict.keys())\n\n document = Document(tweet_id, tweet_date, full_text, url, retweet_text, retweet_url, quote_text,\n quote_url, term_dict, doc_length, tweet_date, unique_term_number, entities, max_tf)\n return document\n","sub_path":"parser_module.py","file_name":"parser_module.py","file_ext":"py","file_size_in_byte":26232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"604226413","text":"# =============================================================================\n# Authors: PAR Government\n# Organization: DARPA\n#\n# Copyright (c) 2016 PAR Government\n# All rights reserved.\n#==============================================================================\nfrom math import log\nimport numpy as np\n\n\ndef packImgBits(img, bits_to_use=16):\n \"\"\"\n :param img:\n :param bits:\n :return:\n @type img: numpy.ndarray\n @type bits: int\n \"\"\"\n shift_bits = img.dtype.itemsize * 8 - bits_to_use\n max_image = np.max(img)\n hist, bin_edges = np.histogram(img, bins=range(max_image + 2), )\n # shift the image histogram to the left to remove unused bins\n # find the second histogram bin that has more than 10 values\n # and subtract it from every pixel value\n adjustment_amount = np.argwhere(hist > 10)[1][0]\n img = np.clip(img.astype('int64') - adjustment_amount, 0, max_image).astype(img.dtype)\n # drop the number of LSBs\n img = np.right_shift(img, shift_bits)\n return img\n\ndef get_gauss_kernel(size=3,sigma=1):\n center=(int)(size/2)\n kernel=np.zeros((size,size))\n for i in range(size):\n for j in range(size):\n diff=np.sqrt((i-center)**2+(j-center)**2)\n kernel[i,j]=np.exp(-(diff**2)/(2*sigma**2))\n return kernel/np.sum(kernel)\n\ndef packImgBitsFFT(img, max_bits=5):\n \"\"\"\n :param img:\n :param bits:\n :return:\n @type img: numpy.ndarray\n @type bits: int\n \"\"\"\n from scipy import fftpack, signal\n amount = (1<<16) if img.dtype == np.uint16 else (1<<8)\n img_output = img.copy()\n kernel = get_gauss_kernel(21,1)\n #freq_kernel = fftpack.fft2(fftpack.ifftshift(kernel))\n for c in range( img.shape[2]):\n im_fft = np.fft.fft2(img[:,:,c])\n convolved = signal.convolve2d(im_fft.real, kernel)\n im_blur = fftpack.ifft2(convolved).real\n diff_x = (im_blur.shape[0] - img_output.shape[0])/2\n diff_y = (im_blur.shape[1] - img_output.shape[1])/2\n img_output[:,:,c] = (amount * im_blur / np.max(im_blur))[diff_x:-diff_x,diff_y:-diff_y]\n return img_output\n\n\ndef packImgBitsS(img, max_bits=5):\n \"\"\"\n :param img:\n :param bits:\n :return:\n @type img: numpy.ndarray\n @type bits: int\n \"\"\"\n from scipy import fftpack, signal\n amount = (1<<16) if img.dtype == np.uint16 else (1<<8)\n\n t = np.linspace(-10, 10, 30)\n bump = np.exp(-0.1 * t ** 2)\n bump /= np.trapz(bump) # normalize the integral to 1\n # make a 2-D kernel out of it\n kernel = bump[:, np.newaxis] * bump[np.newaxis, :]\n kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))\n # convolve\n img_ft = fftpack.fft2(img, axes=(0, 1))\n # the 'newaxis' is to match to color direction\n img2_ft = kernel_ft[:, :, np.newaxis] * img_ft\n img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real\n img_output = img2.copy()\n return img_output","sub_path":"maskgen/algorithms/histogram_changes.py","file_name":"histogram_changes.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"488229118","text":"import numpy as np\n\ninputFile = '../resources/input03.txt'\n\n\n#### PART 1\n\ndef readFile(f):\n\tarray = []\n\twith open(inputFile, 'r') as f:\n\t\tfirst = 0\n\t\tfor line in f:\n\t\t\tif first == 0:\n\t\t\t\tline1 = [x for x in line.split(',')]\n\t\t\t\tfirst = 1\n\t\t\telse:\n\t\t\t\tline2 = [x for x in line.split(',')]\n\n\treturn (line1, line2)\n\n\ndef initiateBoard(boardSize):\n\tboard = np.zeros([boardSize, boardSize])\n\tstationPos = [int(boardSize / 2), int(boardSize / 2)]\n\n\tboard[stationPos[0], stationPos[1]] = 1\n\n\treturn (stationPos, board)\n\n\ndef calcNew(currPos, dir, steps):\n\tnewPos = currPos.copy()\n\tif dir == 'R':\n\t\tnewPos[0] = currPos[0] + steps\n\t\tcurrPos[0] = currPos[0] + 1\n\telif dir == 'L':\n\t\tnewPos[0] = currPos[0] - steps\n\t\tcurrPos[0] = currPos[0] - 1\n\telif dir == 'U':\n\t\tnewPos[1] = currPos[1] - steps\n\t\tcurrPos[1] = currPos[1] - 1\n\telse:\n\t\tnewPos[1] = currPos[1] + steps\n\t\tcurrPos[1] = currPos[1] + 1\n\n\treturn (currPos, newPos)\n\n\ndef drawBoard(dir, c, n, firstWire):\n\tif dir in ['R', 'D']:\n\t\tif firstWire:\n\t\t\tboard[c[1]:(n[1] + 1), c[0]:(n[0] + 1)] = 1\n\t\telse:\n\t\t\taux = board[c[1]:(n[1] + 1), c[0]:(n[0] + 1)]\n\t\t\tboard[c[1]:(n[1] + 1), c[0]:(n[0] + 1)] = np.where(aux == 1, 3, 2)\n\telse:\n\n\t\tif firstWire:\n\t\t\tboard[n[1]:(c[1] + 1), n[0]:(c[0] + 1)] = 1\n\t\telse:\n\t\t\taux = board[n[1]:(c[1] + 1), n[0]:(c[0] + 1)]\n\t\t\tboard[n[1]:(c[1] + 1), n[0]:(c[0] + 1)] = np.where(aux == 1, 3, 2)\n\n\ndef drawWire(wire, initialPos, firstWire):\n\tglobal board\n\tcurrPos = initialPos.copy()\n\n\tfor instr in wire:\n\t\tdir = instr[0]\n\t\tsteps = int(instr[1:])\n\t\tcurrPost, newPos = calcNew(currPos, dir, steps)\n\t\t# print(str(currPos) + ' -> ' + str(newPos) + ' for dir: ' + str(dir) + ', steps:' + str(steps))\n\n\t\tdrawBoard(dir, currPos, newPos, firstWire)\n\t\tcurrPos = newPos.copy()\n\n\ndef calcMinDist(arr1, arr2, board, stationPos, minDist):\n\t# draw both wires\n\tdrawWire(arr1, stationPos, True)\n\tdrawWire(arr2, stationPos, False)\n\n\ta, b = np.where(board == 3)\n\n\tfor i in range(0, len(a)):\n\t\tcurrD = abs(a[i] - stationPos[0]) + abs(b[i] - stationPos[1])\n\t\tif currD < minDist:\n\t\t\tminDist = currD\n\n\treturn (minDist)\n\n\n# arr1, arr2 = readFile(inputFile)\n# print(arr1)\n# print(arr2)\n# arr1 = ['R75','D30','R83','U83','L12','D49','R71','U7','L72']\n# arr2 = ['U62','R66','U55','R34','D71','R55','D58','R83']\n\n# arr1 = ['R98','U47','R26','D63','R33','U87','L62','D20','R33','U53','R51']\n# arr2 = ['U98','R91','D20','R16','D67','R40','U7','R15','U6','R7']\n\n# arr1 = ['R8','U5','L5','D3']\n# arr2 = ['U7','R6','D4','L4']\n\n# size = 20000\n# stationPos, board = initiateBoard(size)\n# d = calcMinDist(arr1, arr2, board, stationPos, size)\n# print('The minimum distance is ' + str(d))\n# 462 is too low\n# 2193\n\n#### PART 2\n\ndef calcNew2(currPos, dir, steps):\n\tnewPos = currPos.copy()\n\tif dir == 'R':\n\t\tnewPos[0] = currPos[0] + steps\n\telif dir == 'L':\n\t\tnewPos[0] = currPos[0] - steps\n\telif dir == 'U':\n\t\tnewPos[1] = currPos[1] - steps\n\telse:\n\t\tnewPos[1] = currPos[1] + steps\n\n\treturn (newPos)\n\ndef isBetween(c, n, i):\n\tif (abs(i[0] - c[0]) <= abs(n[0] - c[0])) and (abs(i[1] - c[1]) <= abs(n[1] - c[1])):\n\t\treturn(True)\n\telse:\n\t\treturn(False)\n\ndef countSteps(wire, initialPos, inters):\n\tglobal board\n\n\tcurrPos = initialPos.copy()\n\tsumSteps = 0\n\t#print('inters:' + str(inters))\n\n\tfor instr in wire:\n\t\tdir = instr[0]\n\t\tsteps = int(instr[1:])\n\t\tnewPos = calcNew2(currPos, dir, steps)\n\n\t\t#stop as soon as the intersection is found\n\t\t#print('positions: ' + str(currPos) + ' -> ' + str(newPos))\n\t\tif isBetween(currPos, newPos, inters):\n\t\t\taux1 = abs(inters[0] - currPos[0])\n\t\t\taux2 = abs(inters[1] - currPos[1])\n\t\t\tsumSteps = sumSteps + aux1 + aux2\n\t\t\t#print('Sum steps to intersection: ' + str(sumSteps))\n\t\t\treturn(sumSteps)\n\t\telse:\n\t\t\tsumSteps = sumSteps + steps\n\t\t\t#print('increasing: ' + str(sumSteps))\n\n\t\tcurrPos = newPos.copy()\n\narr1, arr2 = readFile(inputFile)\n\n#arr1 = ['R8', 'U5', 'L5', 'D3']\n#arr2 = ['U7', 'R6', 'D4', 'L4']\n\n#arr1 = ['R75','D30','R83','U83','L12','D49','R71','U7','L72']\n#arr2 = ['U62','R66','U55','R34','D71','R55','D58','R83']\n\n#arr1 = ['R98','U47','R26','D63','R33','U87','L62','D20','R33','U53','R51']\n#arr2 = ['U98','R91','D20','R16','D67','R40','U7','R15','U6','R7']\n\nsize = 20000\nstationPos, board = initiateBoard(size)\n\n# draw both wires\ndrawWire(arr1, stationPos, True)\ndrawWire(arr2, stationPos, False)\n\n# check intersection coordinates\na, b = np.where(board == 3)\n\ndistSum = []\nfor i in range(0, len(a)):\n\tdist1 = countSteps(arr1, stationPos, [b[i], a[i]])\n\tdist2 = countSteps(arr2, stationPos, [b[i], a[i]])\n\tdistSum.append(dist1 + dist2)\n\nprint(distSum)\nprint('Minimum step-distance is ' + str(np.array(distSum).min()))\n#63526","sub_path":"03day/calAdvento03.py","file_name":"calAdvento03.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"291358842","text":"class Solution(object):\n def gameOfLife(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n\n x = 0\n y = 0\n\n n = len(board)\n for I in range(n):\n for J in range(n):\n \n count = 0\n for i in range(max(0, I - 1), min(n, I + 2)):\n for j in range(max(0, J - 1), min(n, J + 2)):\n count += board[i][j] & 1\n\n if (count == 4 and board[i][j]) or count == 3:\n board[I][J] |= 2\n \n for i in range(n):\n for j in range(n):\n board[i][j] >>= 1\n\n print(board)\nboard = [[0, 0, 0, 0],\n [0, 1, 1, 0],\n [0, 1, 1, 0],\n [0, 0, 0, 0]]\n\nresult = Solution().gameOfLife(board)\nprint(result)\n","sub_path":"game-of-life/game-of-life.py","file_name":"game-of-life.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"415198426","text":"#программа, которая вытаскивает с главной страницы сайта все заголовки и записывает их в файл\r\n\r\nimport urllib.request \r\n\r\nurl = 'http://www.znamyatrud.ru/'\r\nuser_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' \r\nreq = urllib.request.Request('http://www.znamyatrud.ru/', headers={'User-Agent':user_agent}) \r\n\r\nwith urllib.request.urlopen(req) as response:\r\n html = response.read().decode('windows-1251')\r\n\r\nimport re\r\nregPostTitle = re.compile('
.*?', flags=re.U | re.DOTALL)\r\ntitles = regPostTitle.findall(html)\r\n\r\nnew_titles = []\r\nregex = '(<.*?>|[0-9])|\\.'\r\n\r\nfor element in titles:\r\n element = re.sub(regex, '', element)\r\n new_titles.append(element)\r\n\r\nf = open('titles.txt', 'w')\r\nfor t in new_titles:\r\n f.write(t + '\\n')\r\n\r\nf.close()\r\n\r\n","sub_path":"ivanova_hw_1.py","file_name":"ivanova_hw_1.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"609983354","text":"import pandas as pd\r\n\r\nimport numpy as np\r\nfrom kmodes.kmodes import KModes\r\n\r\n\r\n\r\ndf = pd.read_excel('chosen.xlsx')\r\n\r\n#izdvojim bitne kolone\r\n\r\nprint(df.columns)\r\nf = ['Q16RPython', 'Q6', 'Q19_Part_1', 'Q19_Part_2', 'Q19_Part_3','Q13_Part_1', 'Q13_Part_2', 'Q13_Part_3']\r\n\r\n\r\ndf.loc[df['Q19_Part_1'].isna(),'Q19_Part_1']=''\r\ndf.loc[df['Q19_Part_2'].isna(),'Q19_Part_2']=''\r\ndf.loc[df['Q19_Part_3'].isna(),'Q19_Part_3']=''\r\n\r\ndf.loc[df['Q13_Part_1'].isna(),'Q13_Part_1']=''\r\ndf.loc[df['Q13_Part_2'].isna(),'Q13_Part_2']=''\r\ndf.loc[df['Q13_Part_3'].isna(),'Q13_Part_3']=''\r\n\r\n\r\ndf.loc[df['Q6'].isna(),'Q6']=''\r\n\r\n\r\ndata = df[f]\r\nprint(data)\r\n\r\n\r\n\"\"\"\r\ncolumns = ['Q4','Q6', 'Q7']\r\n\r\nq16=['Q16_Part_%d'%i for i in range(1,16)]\r\n\r\nprint(q16)\r\nq19=['Q19_Part_%d'%i for i in range(1,19)]\r\nprint(q19)\r\ncolnames = ['gender', 'education', 'current_role', 'emp_status']\r\n\r\nprint(df[q16]);\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nkm = KModes(n_clusters=7, init='Huang', n_init=5, verbose=1)\r\n\r\nclusters = km.fit_predict(data)\r\n\r\n# Print the cluster centroids\r\nprint(km.cluster_centroids_)\r\n\r\n\r\n\r\n","sub_path":"src/cluster3.py","file_name":"cluster3.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"579619434","text":"\nimport configparser\nimport json\nimport logging\nimport log\nimport os\nfrom sdp import SDP\nimport sys\n\nclass Config(object):\n \"\"\"Configuration container\"\"\"\n \n PREFIX = \"/opt/lthn\"\n OPENVPN_BIN = None\n HAPROXY_BIN = None\n SUDO_BIN = None\n OPENVPN_SUDO = None\n LOGLEVEL = logging.WARNING\n AUDITLOG = None\n VERBOSE = None\n CONFIGFILE = None\n SDPFILE = None\n AUTHIDSFILE = None\n MAINSLEEP = 0.1\n T_SAVE = 10 # How often to save authids (sec)\n T_CLEANUP = 30 # How often to cleanup stale authids\n FORCE_REFRESH = None\n FORCE_SAVE = None\n \n # configargparse results\n CAP = None\n \n def __init__(self, action=\"read\", services=None):\n if (os.getenv('LTHN_PREFIX')):\n type(self).PREFIX = os.getenv('LTHN_PREFIX')\n \n type(self).OPENVPN_BIN = \"/usr/sbin/openvpn\"\n type(self).HAPROXY_BIN = \"/usr/sbin/haproxy\"\n type(self).SUDO_BIN = \"/usr/bin/sudo\"\n type(self).OPENVPN_SUDO = True\n type(self).LOGLEVEL = logging.WARNING\n type(self).CONFIGFILE = type(self).PREFIX + \"/etc/dispatcher.ini\"\n type(self).SDPFILE = type(self).PREFIX + \"/etc/sdp.json\"\n type(self).PIDFILE = type(self).PREFIX + \"/var/run/lthnvpnd.pid\"\n type(self).AUTHIDSFILE = type(self).PREFIX + '/var/authids.db'\n \n s = SDP()\n self.load(self.CONFIGFILE)\n if (action == \"init\"):\n # generate SDP configuration file based on user input\n print('Initialising SDP file %s' % self.SDPFILE)\n s.addService(self.CAP)\n s.configFile = self.SDPFILE\n s.save(self.SDPFILE)\n elif (action == \"read\"):\n self.load(self.CONFIGFILE)\n s.load(self.SDPFILE)\n elif (action == \"dummy\"):\n if (os.path.exists(self.SDPFILE)):\n s.load(self.SDPFILE)\n else:\n logging.warning(\"Missing SDP file\" + self.SDPFILE)\n elif (action == \"edit\"):\n # generate SDP configuration file based on user input\n print('Editing SDP file %s' % self.SDPFILE)\n s.editService(self.CAP)\n print('YOUR CHANGES TO THE SDP CONFIG file ARE UNSAVED!')\n choice = input('Save the file? This will overwrite your existing config file! [y/N] ').strip().lower()[:1]\n if (choice == 'y'):\n s.save()\n elif (action == \"add\"):\n # Add service into SDP file based on user input\n print('Editing configuration file %s' % self.SDPFILE)\n s.addService(self.CAP)\n print('YOUR CHANGES TO THE SDP CONFIG file ARE UNSAVED!')\n choice = input('Save the file? This will overwrite your existing config file! [y/N] ').strip().lower()[:1]\n if (choice == 'y'):\n s.save()\n elif (action == \"upload\"):\n s.load(self.SDPFILE)\n s.upload()\n else:\n logger.error(\"Bad option to Config!\")\n sys.exit(2)\n \n def load(self, filename):\n try:\n logging.debug(\"Reading config file %s\" % (filename))\n cfg = configparser.ConfigParser()\n cfg.read(filename)\n self.cfg = cfg\n except IOError:\n logging.error(\"Cannot read %s. Exiting.\" % (filename))\n sys.exit(1)\n \n def getService(self, id):\n section = \"service-\" + id\n for s in self.cfg.sections():\n if s.lower() == section.lower():\n return(self.cfg[s])\n return(None)\n\nCONFIG = None\n","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"436142187","text":"from reports import config, my_auth, my_reports, output_status_message, output_bing_ads_webfault_error, output_webfault_errors, get_date_range\nfrom datetime import date\nfrom sys import argv\n\nif __name__ == '__main__':\n start_date = ''\n end_date = ''\n\n # validate input\n if len(argv) == 1:\n start_date = date.today().strftime('%m-%d-%Y')\n end_date = start_date\n else:\n start_date = argv[1]\n if len(argv) > 2 :\n end_date = argv[2]\n else:\n end_date = start_date\n\n date_range = get_date_range(start_date, end_date)\n \n if date_range and len(date_range) > 0:\n auth = my_auth()\n authorization_data = auth.authenticate()\n \n for report_date in date_range:\n my_reports(report_date, authorization_data).download_report()","sub_path":"bing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"396807705","text":"#!/usr/bin/env python\n\nimport sys\n\nsys.path.append('/home/song/PycharmProjects/SongNCM') # need add path at terminal\n\nimport logging\nfrom mininet.net import Mininet\nfrom mininet.node import RemoteController\nfrom mininet.cli import CLI\nfrom mininet.link import TCLink\nfrom Tools.CreateTopology import SwitchHostLink\n\ndef createTopo():\n logging.debug(\"create 2 switch and 3 host\")\n\n topo = SwitchHostLink(2, 3)\n topo.createTopo()\n topo.createLink(topo.switchlist[0], topo.hostlist[0])\n topo.createLink(topo.switchlist[0], topo.hostlist[1])\n topo.createLink(topo.switchlist[0], topo.switchlist[1])\n topo.createLink(topo.switchlist[1], topo.hostlist[2])\n\n controller_ip = \"127.0.0.1\"\n controller_port = 6633\n net = Mininet(topo=topo, link=TCLink, controller=None, autoSetMacs=True)\n net.addController('controller', controller=RemoteController,\n ip=controller_ip, port=controller_port)\n net.start()\n\n # topo.open_service(net)\n\n CLI(net)\n net.stop()\n\n\nif __name__ == '__main__':\n createTopo()\n","sub_path":"topology/s2_h3.py","file_name":"s2_h3.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"402362558","text":"#Uses python3\n\nimport sys\nimport time\n\nsys.setrecursionlimit(200000)\n\ncount = 1\n\ndef graphorder(vertex,graph,visited,post):\n global count\n visited[vertex] = True\n count += 1\n for node in graph[vertex]:\n if visited[node] is False:\n graphorder(node,graph,visited,post)\n post[vertex] = count\n count += 1\n\ndef dfs(graph): \n post = [0 for _ in range(n)]\n visited = [False for _ in range(n)]\n for i in range(n):\n if visited[i] is False:\n graphorder(i,graph,visited,post)\n return post\n\ndef explore_scc(vertex,graph,scc,visited,post):\n visited[vertex] = True\n scc.add(post[vertex])\n \n for node in graph[vertex]:\n if visited[node] is False:\n explore_scc(node,graph,scc,visited,post)\n\n\ndef find_all_scc(graph,post):\n visited = [False for _ in range(n)]\n rem_nodes = sorted([(i,j) for i,j in enumerate(post)],key=lambda k:k[1],reverse=True) \n result = 0\n\n while len(rem_nodes) != 0:\n scc = set() \n max_index = rem_nodes[0][0]\n explore_scc(max_index,graph,scc,visited,post)\n result += 1\n rem_nodes = [t for t in rem_nodes if t[1] not in scc] \n return result\n\n\ndef number_of_strongly_connected_components(actual_graph,reverse_graph): \n\n #t0 = time.time()\n # Post Order for Reverse Graph\n graphpostorder = dfs(reverse_graph)\n \n\n # Find All SCC on actual graph based of post order\n components = find_all_scc(actual_graph,graphpostorder) \n \n #t1 = time.time()\n\n #print(t1-t0)\n #print(\"Components :\",components)\n return components\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n, m = data[0:2]\n data = data[2:]\n edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))\n actual_graph = [[] for _ in range(n)]\n reverse_graph = [[] for _ in range(n)]\n for (a, b) in edges:\n actual_graph[a - 1].append(b - 1)\n reverse_graph[b-1].append(a-1)\n print(number_of_strongly_connected_components(actual_graph,reverse_graph))\n","sub_path":"graphs/Week-2/strongly_connected/strongly_connected.py","file_name":"strongly_connected.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"345713880","text":"\"\"\"\n Create a contour plot of monthly precip from the climodat data (iemre)\n\"\"\"\nimport sys\nimport datetime\n\nimport psycopg2.extras\nfrom pyiem.network import Table as NetworkTable\nfrom pyiem.plot import MapPlot\nfrom pyiem.util import get_dbconn\n\n\ndef do_month(ts, routes=\"m\"):\n \"\"\"\n Generate the plot for a given month, please\n \"\"\"\n pgconn = get_dbconn(\"coop\", user=\"nobody\")\n ccursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n nt = NetworkTable(\"IACLIMATE\")\n sql = \"\"\"SELECT station, sum(precip) as total, max(day) as lastday\n from alldata_ia WHERE year = %s and month = %s\n and station != 'IA0000' and substr(station,2,1) != 'C'\n GROUP by station\"\"\" % (\n ts.year,\n ts.month,\n )\n\n lats = []\n lons = []\n vals = []\n lastday = None\n ccursor.execute(sql)\n for row in ccursor:\n if row[\"station\"] not in nt.sts:\n continue\n if lastday is None:\n lastday = row[\"lastday\"]\n lats.append(nt.sts[row[\"station\"]][\"lat\"])\n lons.append(nt.sts[row[\"station\"]][\"lon\"])\n vals.append(row[\"total\"])\n\n mp = MapPlot(\n title=\"%s - %s\"\n % (ts.strftime(\"%d %B %Y\"), lastday.strftime(\"%d %B %Y\")),\n subtitle=\"%s Total Precipitation [inch]\" % (ts.strftime(\"%B %Y\"),),\n )\n mp.contourf(\n lons, lats, vals, [0, 0.1, 0.25, 0.5, 0.75, 1, 2, 3, 4, 5, 6, 7]\n )\n mp.plot_values(lons, lats, vals, fmt=\"%.2f\")\n\n pqstr = (\n \"plot %s %s summary/iemre_iowa_total_precip.png \"\n \"%s/summary/iemre_iowa_total_precip.png png\"\n ) % (routes, ts.strftime(\"%Y%m%d%H%M\"), ts.strftime(\"%Y/%m\"))\n mp.postprocess(pqstr=pqstr)\n\n\ndef main(argv):\n \"\"\"Do Something\"\"\"\n if len(argv) == 3:\n now = datetime.datetime(int(argv[1]), int(argv[2]), 1)\n do_month(now, \"m\")\n else:\n now = datetime.datetime.now() - datetime.timedelta(days=1)\n now = now.replace(day=1)\n do_month(now, \"cm\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"scripts/climodat/plot_monthly_precip.py","file_name":"plot_monthly_precip.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"246733533","text":"import sys\nimport tensorflow as tf\nsys.path.append(sys.path[0][:-10])\nfrom model.chatter import Chatter\nimport model.seq2seq as seq2seq\nfrom common.utils import CmdParser\nimport config.get_config as _config\nfrom common.pre_treat import preprocess_raw_lccc_data\n\n\nclass Seq2SeqChatter(Chatter):\n \"\"\"\n Seq2Seq模型的聊天类\n \"\"\"\n\n def __init__(self, model, checkpoint_dir, beam_size, vocab_size):\n \"\"\"\n Seq2Seq聊天器初始化,用于加载模型\n \"\"\"\n super().__init__(model, checkpoint_dir, beam_size)\n self.encoder = seq2seq.Encoder(vocab_size, _config.embedding_dim, _config.units, _config.BATCH_SIZE)\n self.decoder = seq2seq.Decoder(vocab_size, _config.embedding_dim, _config.units, _config.BATCH_SIZE)\n self.optimizer = tf.keras.optimizers.Adam()\n self.loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction='none')\n self.checkpoint = tf.train.Checkpoint(optimizer=self.optimizer, encoder=self.encoder, decoder=self.decoder)\n\n print('正在检查是否存在检查点...')\n if self.ckpt:\n print('存在检查点,正在从{}中加载检查点'.format(checkpoint_dir))\n self.checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir)).expect_partial()\n else:\n print('不存在检查点,请先执行train模式,再进入chat模式')\n if model == 'chat':\n exit(0)\n\n def _train_step(self, inp, tar, weight, step_loss):\n loss = 0\n enc_hidden = self.encoder.initialize_hidden_state()\n\n with tf.GradientTape() as tape:\n enc_output, enc_hidden = self.encoder(inp, enc_hidden)\n dec_hidden = enc_hidden\n # 这里初始化decoder的输入,首个token为start,shape为(128, 1)\n dec_input = tf.expand_dims([2] * _config.BATCH_SIZE, 1)\n # 这里针对每个训练出来的结果进行损失计算\n for t in range(1, tar.shape[1]):\n predictions, dec_hidden, _ = self.decoder(dec_input, dec_hidden, enc_output)\n loss += self._loss_function(tar[:, t], predictions, weight)\n # 这一步使用teacher forcing\n dec_input = tf.expand_dims(tar[:, t], 1)\n\n batch_loss = (loss / int(tar.shape[1]))\n variables = self.encoder.trainable_variables + self.decoder.trainable_variables\n gradients = tape.gradient(loss, variables)\n self.optimizer.apply_gradients(zip(gradients, variables))\n\n step_loss[0] += batch_loss\n\n def _create_predictions(self, inputs, dec_input, t):\n hidden = tf.zeros((inputs.shape[0], _config.units))\n enc_out, enc_hidden = self.encoder(inputs, hidden)\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims(dec_input[:, t], 1)\n predictions, _, _ = self.decoder(dec_input, dec_hidden, enc_out)\n return predictions\n\n def _loss_function(self, real, pred, weights):\n \"\"\"\n :param real:\n :param pred:\n :return: loss\n \"\"\"\n # 这里进来的real和pred的shape为(128,)\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = self.loss_object(real, pred, sample_weight=weights)\n # 这里要注意了,因为前面我们对于短的句子进行了填充,所\n # 以对于填充的部分,我们不能用于计算损失,所以要mask\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n return tf.reduce_mean(loss_)\n\n\ndef get_chatter(model):\n # 初始化要使用的聊天器\n chatter = Seq2SeqChatter(model=model,\n checkpoint_dir=_config.seq2seq_train_data,\n beam_size=_config.beam_size,\n vocab_size=_config.vocab_size,\n dict_fn=_config.seq2seq_dict_fn)\n return chatter\n\n\ndef main():\n parser = CmdParser(version='%seq2seq chatbot V1.0')\n parser.add_option(\"-t\", \"--type\", action=\"store\", type=\"string\",\n dest=\"type\", default=\"pre_treat\",\n help=\"execute type, pre_treat/train/chat\")\n (options, args) = parser.parse_args()\n\n if options.type == 'train':\n chatter = get_chatter(options.type)\n chatter.train(chatter.checkpoint,\n dict_fn=_config.seq2seq_dict_fn,\n data_fn=_config.data,\n max_train_data_size=_config.max_train_data_size)\n elif options.type == 'chat':\n chatter = get_chatter(options.type)\n print(\"Agent: 你好!结束聊天请输入ESC。\")\n while True:\n req = input(\"User: \")\n if req == \"ESC\":\n print(\"Agent: 再见!\")\n exit(0)\n response = chatter.respond(req=req)\n print(\"Agent: \", response)\n elif options.type == 'pre_treat':\n preprocess_raw_lccc_data(raw_data=_config.transformer_lccc_data,\n tokenized_data=_config.transformer_lccc_tokenized_data)\n # preprocess_raw_data(raw_data=_config.resource_data, tokenized_data=_config.tokenized_data)\n else:\n parser.error(msg='')\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Seq2Seq入口:指令需要附带运行参数\n cmd:python seq2seq2_chatter.py -t/--type [执行模式]\n 执行类别:pre_treat/train/chat\n\n chat模式下运行时,输入ESC即退出对话\n \"\"\"\n main()\n","sub_path":"hlp/chat/free/seq2seq_chatter.py","file_name":"seq2seq_chatter.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"260988998","text":"import os\n\nfrom keras import optimizers, regularizers\nimport keras\nfrom keras.callbacks import LearningRateScheduler, TensorBoard, ModelCheckpoint\nfrom keras.datasets import cifar10\nfrom keras.initializers import he_normal\nfrom keras.layers import Dense, Input, add, Activation, GlobalAveragePooling2D\n\nfrom keras.layers.core import Flatten, Dropout\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import MaxPooling2D, AveragePooling2D\nfrom keras.models import Model, load_model, Sequential\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy\n\nimport keras.backend as K\nimport numpy as np\n\n# from keras.layers.convolutional import Conv2D\nfrom operations import Convolution2D as Conv2D\n \nfrom utills import load_cifar, load_cifar_100\nfrom keras.layers.merge import Concatenate\n\n\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nK.set_image_dim_ordering('tf')\n\n# from keras.layers import Conv2D\n\n\n\nstack_n = 5 \nnum_classes = 10\nimg_rows, img_cols = 32, 32\nimg_channels = 3\nbatch_size = 128\nepochs = 200\niterations = 50000 // batch_size\nweight_decay = 0.0001\ndropout = 0.5\nmean = [125.307, 122.95, 113.865]\nstd = [62.9932, 62.0887, 66.7048]\n\ndef scheduler(epoch):\n if epoch < 80:\n return 0.1\n if epoch < 150:\n return 0.01 \n return 0.001\n\n# he_normal = truncated_normal\n\n# build model\ninput = Input(shape=[32,32,3])\n\n\n# Block 1\nx = Conv2D(8, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block1_conv1', input_shape=[32,32,3])(input)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(8, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block1_conv2')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n# Block 2\nx = Conv2D(16, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block2_conv1')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(16, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block2_conv2')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n# Block 3\nx = Conv2D(32, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block3_conv1')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(32, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block3_conv2')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(32, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block3_conv3')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(32, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block3_conv4')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n# Block 4\nx = Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block4_conv1')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block4_conv2')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block4_conv3')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(64, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block4_conv4')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n# Block 5\nx = Conv2D(128, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block5_conv1')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(128, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block5_conv2')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(128, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block5_conv3')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(128, (3, 3), padding='same', kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='block5_conv4')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n# model modification for cifar-10\nx = Flatten(name='flatten')(x)\nx = Dense(1024, use_bias = True, kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='fc_cifa10')(x)\nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Dropout(dropout)(x)\nx = Dense(1024, kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='fc2')(x) \nx = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Dropout(dropout)(x) \nx = Dense(100, kernel_regularizer=keras.regularizers.l2(weight_decay), kernel_initializer=he_normal(), name='predictions_cifa10')(x) \nx = BatchNormalization()(x)\noutput = Activation('softmax')(x)\n\nmodel = Model(input,output)\n\n\ndef color_preprocessing(x_train,x_test):\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n for i in range(3):\n x_train[:,:,:,i] = (x_train[:,:,:,i] - mean[i]) / std[i]\n x_test[:,:,:,i] = (x_test[:,:,:,i] - mean[i]) / std[i]\n return x_train, x_test\n\nif __name__ == '__main__':\n# # load data\n# # (x_train, y_train), (x_test, y_test) = cifar10.load_data(r'F:\\AAA_workspace\\dataset\\cifar-10-batches-py')\n# # y_train = keras.utils.to_categorical(y_train, num_classes)\n# # y_test = keras.utils.to_categorical(y_test, num_classes)\n# \n\n\n\n\n \n (x_train, y_train), (x_test, y_test) = load_cifar_100()\n# \n# # # color preprocessing\n x_train, x_test = color_preprocessing(x_train, x_test)\n# \n # build network\n \n print(model.summary())\n \n # set optimizer\n sgd = optimizers.SGD(lr=.1, momentum=0.9, nesterov=True)\n# sgd = optimizers.Adam()\n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n \n # set callback\n cbks = [TensorBoard(log_dir='./resnet_32/', histogram_freq=0),\n LearningRateScheduler(scheduler),\n ModelCheckpoint('./checkpoint-{epoch}.h5', save_best_only=False, mode='auto', period=10)]\n \n # set data augmentation\n print('Using real-time data augmentation.')\n datagen = ImageDataGenerator(horizontal_flip=True,\n width_shift_range=0.125,\n height_shift_range=0.125,\n fill_mode='constant',cval=0.)\n datagen.fit(x_train)\n \n # start training\n model.fit_generator(datagen.flow(x_train, y_train,batch_size=batch_size),\n steps_per_epoch=iterations,\n epochs=epochs,\n callbacks=cbks,\n validation_data=(x_test, y_test))\n\n# resnet = load_model('resnet_2.h5')\n# # r = resnet.evaluate(x_test, y_test,1)\n# r = resnet.predict(x_test, 100)\n# r = numpy.argmax(r,1)==numpy.argmax(y_test,1)\n# r = numpy.mean(r.astype('float32'))\n# print(r)\n\n\n \n ","sub_path":"cifar-100/vgg_19_FWD.py","file_name":"vgg_19_FWD.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"5583032","text":"import itertools\n\nS = input()\n\n\ndef solve():\n ans = []\n ss = itertools.groupby(S)\n\n for key, groups in ss:\n groups = list(groups)\n groups_cnt = len(groups)\n nothing_group = [0] * (groups_cnt - 1)\n\n even_cnt = groups_cnt // 2\n odd_cnt = groups_cnt - even_cnt\n\n if key == 'R':\n tmp_ans = nothing_group + [odd_cnt]\n tmp_ans.append(even_cnt)\n elif key == 'L':\n ans[-1] += odd_cnt\n ans[-2] += even_cnt\n tmp_ans = nothing_group\n\n ans += tmp_ans\n\n print(*ans)\n\n\nsolve()\n","sub_path":"contest_abc/136/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}