diff --git "a/589.jsonl" "b/589.jsonl" new file mode 100644--- /dev/null +++ "b/589.jsonl" @@ -0,0 +1,675 @@ +{"seq_id":"377286149","text":"# Given a string, find if there is any sub-sequence of length at least 2 that repeats itself.\n\n\ndef anytwo(A):\n subs = []\n for i in range(len(A)):\n for j in range(i):\n sub = A[j]+A[i]\n for t in subs:\n if t[0] == sub and t[1] != j and t[2] != i:\n return True\n subs.append((sub,j,i))\n return False\n\n### Tests\nassert anytwo('abab')\nassert not anytwo('abba')\nassert anytwo('aaa')\nassert anytwo('abcac')\nassert not anytwo('abcde')\nassert not anytwo('abcdcba')\n","sub_path":"interviewbit/dynamic-programming/repeatingSubsequence.py","file_name":"repeatingSubsequence.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"261798186","text":"def countSort(array):\n \"\"\"\"\n There are onlu numbers greater or equal to 0 in the array.\n 1) counts quantity of every value in the array by creating a list \n where every position equals to a counting value \n and the number written in this position is a number of this value.\n 2) creates sorted list using counters list by generating values \n equal to the every position and generates them \n as many times as indicated in the position in counters.\n \"\"\"\n counters = []\n for n in array:\n try:\n counters[n] = counters[n] + 1\n except IndexError:\n last_index = len(counters)\n while (last_index) < n:\n counters.append(0)\n last_index += 1\n counters.append(1)\n array = []\n position = 0\n for c in counters:\n for i in range(1, c+1):\n array.append(position)\n position += 1\n return array\n\n\na = [5, 7, 3, 8, 2, 3, 7, 9, 0, 6, 0, 1, 4, 17, 28]\nprint(countSort(a))\n","sub_path":"sort/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"640020846","text":"from novaclient.v2.servers import Server as NovaServer\n\nfrom cloudshell.cp.core.cancellation_manager import CancellationContextManager\n\nfrom cloudshell.cp.openstack.models import OSNovaImgDeployApp\nfrom cloudshell.cp.openstack.os_api.api import OSApi\nfrom cloudshell.cp.openstack.os_api.commands.rollback import (\n RollbackCommand,\n RollbackCommandsManager,\n)\n\n\nclass CreateInstanceCommand(RollbackCommand):\n def __init__(\n self,\n rollback_manager: RollbackCommandsManager,\n cancellation_manager: CancellationContextManager,\n os_api: OSApi,\n deploy_app: OSNovaImgDeployApp,\n *args,\n **kwargs\n ):\n super().__init__(rollback_manager, cancellation_manager, *args, **kwargs)\n self._api = os_api\n self._deploy_app = deploy_app\n self._instance = None\n\n def _execute(self, *args, **kwargs) -> NovaServer:\n self._instance = self._api.create_instance(\n self._deploy_app, self._cancellation_manager\n )\n return self._instance\n\n def rollback(self):\n self._api.terminate_instance(self._instance)\n","sub_path":"cloudshell/cp/openstack/os_api/commands/create_instance.py","file_name":"create_instance.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"558915597","text":"from models import Targets,Scans,Services\nimport logging\nimport datetime\n\ndef group_expand(g):\n \n ips=list()\n \n x=Targets.objects.filter(group__group_name__exact=g)\n \n for i in x:\n #ipaddress_str=str(i.ipaddress)\n ips.insert(0,i.ipaddress)\n \n logging.critical(\"nose\")\n logging.critical(ips)\n return ips\n\n\ndef html_report_gen(scan_list):\n \n report=\"\"\n \n\n x=Scans.objects.get(id=scan_list[0])\n scan_ptr=x.id\n \n report += \"
Starting Nmap \" + str(x.nmap_version) + \" ( http://nmap.org ) at \" + str(x.scan_start_time) + \"
\"\n\n for sss in scan_list:\n\n y=Scans.objects.get(id=sss)\n tgt=y.target_id\n target=Targets.objects.filter(id=tgt) \n \n for host in target:\n \n if len(host.hostname):\n tmp_host = \"Host is {0}.\".format(xx.host_status) + \"
\"\n \n report += \"| PORT | PROTOCOL | STATE | SERVICE | BANNER |
|---|---|---|---|---|
| \" + str(serv.port) + \" | \"\n report += \"\" + str(serv.protocol) + \" | \"\n report += \"\" + str(serv.port_status) + \" | \"\n report += \"\" + str(serv.service) + \" | \"\n report += \"\" + str(serv.banner) + \" | \"\n report += \"
\" + x.summary_text + \"
\"\n\n return report","sub_path":"composcan/cps/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"211288074","text":"import logging\n\n# Package imports\nimport irrad_control.devices.ic.ADS1256.ADS1256_definitions as ADS1256_defs\nimport irrad_control.devices.ic.ADS1256.pipyadc as pipyadc\n\n\nclass ADCBoard(object):\n\n drates = dict([(30000, ADS1256_defs.DRATE_30000),\n (15000, ADS1256_defs.DRATE_15000),\n (7500, ADS1256_defs.DRATE_7500),\n (3750, ADS1256_defs.DRATE_3750),\n (2000, ADS1256_defs.DRATE_2000),\n (1000, ADS1256_defs.DRATE_1000),\n (500, ADS1256_defs.DRATE_500),\n (100, ADS1256_defs.DRATE_100),\n (60, ADS1256_defs.DRATE_60),\n (50, ADS1256_defs.DRATE_50),\n (30, ADS1256_defs.DRATE_30),\n (25, ADS1256_defs.DRATE_25),\n (15, ADS1256_defs.DRATE_15),\n (10, ADS1256_defs.DRATE_10),\n (5, ADS1256_defs.DRATE_5),\n (2.5, ADS1256_defs.DRATE_2_5)])\n\n @property\n def drate(self):\n hw_drate = self.adc.drate\n decimal_drate = [k for k, v in self.drates.items() if v == hw_drate]\n return decimal_drate[0]\n\n @drate.setter\n def drate(self, val):\n if val in self.drates:\n self.adc.drate = self.drates[val]\n else:\n msg = \"{} not in available data rates: {}\".format(val, ', '.join(str(k) for k in self.drates))\n msg += \" No changes applied.\"\n logging.warning(msg)\n\n def __init__(self):\n\n # Initialize ADS1256\n self.adc = pipyadc.ADS1256()\n\n # Self calibrate\n self.adc.cal_self()\n\n # Define (positive) input pins\n self.input_pins = (ADS1256_defs.POS_AIN0, ADS1256_defs.POS_AIN1,\n ADS1256_defs.POS_AIN2, ADS1256_defs.POS_AIN3,\n ADS1256_defs.POS_AIN4, ADS1256_defs.POS_AIN5,\n ADS1256_defs.POS_AIN6, ADS1256_defs.POS_AIN7)\n\n # Define respective ground pin\n self.gnd_pin = ADS1256_defs.NEG_AINCOM\n\n self._adc_channels = []\n\n def setup_channels(self, channels_nums):\n\n self._adc_channels = []\n\n # Assign the physical channel numbers e.g. multiplexer address\n for ch in channels_nums:\n\n # Single-ended versus common ground gnd\n if isinstance(ch, int):\n channel = self.input_pins[ch] | self.gnd_pin\n # Differential measurement\n else:\n a, b = ch\n channel = self.input_pins[a] | self.input_pins[b]\n\n # Add to channels\n self._adc_channels.append(channel)\n\n def read_channels(self, channel_names=None):\n\n result = {}\n ch_names = channel_names if channel_names is not None else list(range(len(self._adc_channels)))\n\n if self._adc_channels:\n\n raw_data = self.adc.read_sequence(self._adc_channels)\n\n for i, raw_d in enumerate(raw_data):\n result[ch_names[i]] = raw_d * self.adc.v_per_digit\n\n else:\n logging.warning(\"No input channels to read from are setup. Use 'setup_channels' method\")\n\n return result\n","sub_path":"irrad_control/devices/readout/adc_board.py","file_name":"adc_board.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"566187300","text":"# Oscar Alejandro Torres Maya, A01377686\n# Leer los lados de los triángulos y decir que tipo de triángulo es\n\n# Condición para que sea triángulo rectángulo\ndef trianguloRectangulo(lado1,lado2,lado3):\n if lado1 > lado2 and lado1 > lado3:\n hyp = ((lado3**2)+(lado2**2))**0.5\n return hyp\n elif lado2 > lado1 and lado2 > lado3:\n hyp = ((lado1 ** 2) + (lado3 ** 2)) ** 0.5\n return hyp\n elif lado3 > lado1 and lado3 > lado2:\n hyp = ((lado1 ** 2) + (lado2 ** 2)) ** 0.5\n return hyp\n\n\n# Función principal\ndef main():\n lado1 = float(input(\"Cuál es el primer lado del triángulo? \"))\n lado2 = float(input(\"Cuál es el segundo lado del triángulo? \"))\n lado3 = float(input(\"Cuál es el tercer lado del triángulo? \"))\n triangulo = trianguloRectangulo(lado1,lado2,lado3)\n\n if lado1 <= 0 and lado2 <= 0 and lado3 <= 0:\n print(\"Estos lados no corresponden a un triángulo\")\n\n elif lado1 == lado2 and lado2 == lado3 and lado3 == lado1:\n print(\"El triángulo es equilatero\")\n\n elif lado2 == lado3 or lado1 == lado2 or lado3 == lado1:\n print(\"El triángulo es isóceles\")\n\n elif triangulo == lado1 or triangulo == lado2 or triangulo == lado3:\n print(\"El triángulo es un triángulo rectángulo\")\n else:\n print(\"Este triángulo no es equilatero, ni isóceles y ni triángulo rectángulo\")\n\n# Llamada de función principal\nmain()","sub_path":"Triangulos.py","file_name":"Triangulos.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"288457216","text":"\"\"\" This module contains all functions related to the estimation of the\n generalized Roy model.\n\"\"\"\n\n# standard library\nimport sys\nimport numpy as np\nimport statsmodels.api as sm\nfrom scipy.stats import norm\nfrom scipy.optimize import minimize\n\n# project library\nfrom tools.economics.clsAgent import AgentCls\n\n''' Main function '''\n\n\ndef estimate(init_dict):\n \"\"\" Estimate our version of the generalized Roy model.\n \"\"\"\n # Antibugging\n assert (isinstance(init_dict, dict))\n\n # Load dataset\n Y, D, X, Z, agent_objs = _load_data(init_dict)\n\n # Create auxiliary objects\n start = init_dict['ESTIMATION']['start']\n maxiter = init_dict['ESTIMATION']['maxiter']\n\n optimizer = init_dict['ESTIMATION']['algorithm']\n version = init_dict['ESTIMATION']['version']\n num_covars_out = init_dict['AUX']['num_covars_out']\n\n # Initialize different starting values\n x0 = _get_start(start, init_dict, Y, D, X, Z)\n\n # Select optimizer\n if optimizer == 'nm':\n\n optimizer = 'Nelder-Mead'\n\n elif optimizer == 'bfgs':\n\n optimizer = 'BFGS'\n\n # Provide additional arguments to the optimizer\n opts = dict()\n\n opts['maxiter'] = maxiter\n\n # Run optimization or just evaluate function at starting values\n if maxiter == 0:\n\n # Collect maximization arguments.\n rslt = _distribute_parameters(np.array(x0), init_dict, num_covars_out)\n\n # Calculate likelihood according to user's request\n likl = _negative_log_likelihood(rslt, Y, D, X, Z, agent_objs, version)\n\n # Compile results\n x_rslt, fun, success = x0, likl, False\n\n else:\n\n # Check out the SciPy documentation for details about the interface\n # to the `minimize' function that provides a convenient interface to\n # a variety of alternative maximization algorithms. You will also\n # find information about the return information.\n opt_rslt = minimize(_max_interface, x0,\n args=(Y, D, X, Z, agent_objs, version, init_dict),\n method=optimizer, options=opts)\n\n # Compile results\n x_rslt, fun = opt_rslt['x'], opt_rslt['fun']\n success = opt_rslt['success']\n\n # Tranformation to internal parameters\n rslt = _distribute_parameters(x_rslt, init_dict, num_covars_out)\n\n rslt['fval'], rslt['success'] = fun, success\n\n # Finishing\n return rslt\n\n\n''' Auxiliary functions '''\n# Note that the name of all auxiliary functions starts with an underscore.\n# This ensures that the function is private to the module. A standard import\n# of this module will not make this function available.\n\n\ndef _distribute_parameters(x, init_dict, num_covars_out):\n \"\"\" Distribute the parameters.\n \"\"\"\n # Antibugging\n assert (isinstance(x, np.ndarray))\n assert (isinstance(num_covars_out, int))\n assert (num_covars_out > 0)\n\n # Initialize containers\n rslt = dict()\n\n rslt['TREATED'] = dict()\n rslt['UNTREATED'] = dict()\n rslt['COST'] = dict()\n rslt['DIST'] = dict()\n\n # Distribute parameters\n rslt['TREATED']['all'] = x[:num_covars_out]\n rslt['UNTREATED']['all'] = x[num_covars_out:(2 * num_covars_out)]\n\n rslt['COST']['all'] = x[(2 * num_covars_out):(-4)]\n rslt['COST']['sd'] = init_dict['COST']['sd']\n\n rslt['TREATED']['sd'] = np.exp(x[(-4)])\n rslt['UNTREATED']['sd'] = np.exp(x[(-3)])\n\n rslt['DIST']['rho1'] = -1.0 + 2.0 / (1.0 + float(np.exp(-x[-2])))\n rslt['DIST']['rho0'] = -1.0 + 2.0 / (1.0 + float(np.exp(-x[-1])))\n\n # Update auxiliary versions\n rslt['AUX'] = dict()\n\n rslt['AUX']['x_internal'] = x.copy()\n rslt['AUX']['x_internal'][-4] = np.exp(x[(-4)])\n rslt['AUX']['x_internal'][-3] = np.exp(x[(-3)])\n rslt['AUX']['x_internal'][-2] = -1.0 + 2.0 / (1.0 + float(np.exp(-x[-2])))\n rslt['AUX']['x_internal'][-1] = -1.0 + 2.0 / (1.0 + float(np.exp(-x[-1])))\n\n rslt['AUX']['init_values'] = init_dict['AUX']['init_values']\n\n # Finishing.\n return rslt\n\n\ndef _max_interface(x, Y, D, X, Z, agent_objs, version, init_dict):\n \"\"\" Interface to the SciPy maximization routines.\n \"\"\"\n # Auxiliary objects\n try:\n num_covars_out = X.shape[1]\n except AttributeError:\n num_covars_out = len(agent_objs[0].attr['exog']['outcome'])\n\n # Collect maximization arguments\n rslt = _distribute_parameters(x, init_dict, num_covars_out)\n\n # Calculate likelihood\n likl = _negative_log_likelihood(rslt, Y, D, X, Z, agent_objs, version)\n\n # Finishing.\n return likl\n\n\ndef _negative_log_likelihood(args, Y, D, X, Z, agent_objs, version):\n \"\"\" Negative log-likelihood evaluation.\n \"\"\"\n\n # Select version\n if version == 'slow':\n likl = _slow_negative_log_likelihood(args, Y, D, X, Z)\n elif version == 'fast':\n likl = _fast_negative_log_likelihood(args, Y, D, X, Z)\n elif version == 'object':\n likl = _object_negative_log_likelihood(args, agent_objs)\n else:\n raise AssertionError\n\n # Finishing\n return likl\n\n\ndef _object_negative_log_likelihood(args, agent_objs):\n \"\"\" Negative Log-likelihood function of the generalized Roy model.\n \"\"\"\n\n num_agents = len(agent_objs)\n\n likl = np.tile(np.nan, num_agents)\n\n for i, agent_obj in enumerate(agent_objs):\n\n agent_obj.unlock()\n\n agent_obj.set_economic_environment(args)\n\n agent_obj.lock()\n\n likl[i] = agent_obj._calculate_individual_likelihood()\n\n # Transformations.\n likl = -np.mean(np.log(np.clip(likl, 1e-20, np.inf)))\n\n # Quality checks.\n assert (isinstance(likl, float))\n assert (np.isfinite(likl))\n\n # Finishing.\n return likl\n\n\ndef _slow_negative_log_likelihood(args, Y, D, X, Z):\n \"\"\" Negative Log-likelihood function of the generalized Roy model.\n \"\"\"\n # Distribute arguments\n Y1_coeffs, Y0_coeffs, C_coeffs, choice_coeffs, U1_sd, U0_sd, U1V_rho, \\\n U0V_rho, V_sd = _distribute_arguments(args)\n\n # Auxiliary objects\n num_agents = Y.shape[0]\n\n # Initialize containers\n likl = np.tile(np.nan, num_agents)\n choice_idx = np.tile(np.nan, num_agents)\n\n # Likelihood construction.\n for i in range(num_agents):\n\n g = np.concatenate((X[i, :], Z[i,:]))\n choice_idx[i] = np.dot(choice_coeffs, g)\n\n # Select outcome information\n if D[i] == 1.00:\n coeffs, rho, sd = Y1_coeffs, U1V_rho, U1_sd\n else:\n coeffs, rho, sd = Y0_coeffs, U0V_rho, U0_sd\n\n arg_one = (Y[i] - np.dot(coeffs, X[i, :])) / sd\n arg_two = (choice_idx[i] - rho * V_sd * arg_one) / \\\n np.sqrt((1.0 - rho ** 2) * V_sd**2)\n\n pdf_evals, cdf_evals = norm.pdf(arg_one), norm.cdf(arg_two)\n\n if D[i] == 1.0:\n contrib = (1.0 / float(sd)) * pdf_evals * cdf_evals\n else:\n contrib = (1.0 / float(sd)) * pdf_evals * (1.0 - cdf_evals)\n\n likl[i] = contrib\n\n # Transformations.\n likl = -np.mean(np.log(np.clip(likl, 1e-20, np.inf)))\n\n # Quality checks.\n assert (isinstance(likl, float))\n assert (np.isfinite(likl))\n\n # Finishing.\n return likl\n\n\ndef _fast_negative_log_likelihood(args, Y, D, X, Z):\n \"\"\" Negative Log-likelihood function of the Generalized Roy Model.\n \"\"\"\n # Distribute arguments\n Y1_coeffs, Y0_coeffs, C_coeffs, choice_coeffs, U1_sd, U0_sd, U1V_rho, \\\n U0V_rho, V_sd = _distribute_arguments(args)\n\n # Likelihood construction.\n G = np.concatenate((X, Z), axis=1)\n choice_idx = np.dot(choice_coeffs, G.T)\n\n arg_one = D * (Y - np.dot(Y1_coeffs, X.T)) / U1_sd + \\\n (1 - D) * (Y - np.dot(Y0_coeffs, X.T)) / U0_sd\n\n arg_two = D * (choice_idx - V_sd * U1V_rho * arg_one) / np.sqrt(\n (1.0 - U1V_rho ** 2) * V_sd**2) + \\\n (1 - D) * (choice_idx - V_sd * U0V_rho * arg_one) / np.sqrt(\n (1.0 - U0V_rho ** 2) * V_sd**2)\n\n pdf_evals, cdf_evals = norm.pdf(arg_one), norm.cdf(arg_two)\n\n likl = D * (1.0 / U1_sd) * pdf_evals * cdf_evals + \\\n (1 - D) * (1.0 / U0_sd) * pdf_evals * (1.0 - cdf_evals)\n\n # Transformations.\n likl = -np.mean(np.log(np.clip(likl, 1e-20, np.inf)))\n\n # Quality checks.\n assert (isinstance(likl, float))\n assert (np.isfinite(likl))\n\n # Finishing.\n return likl\n\n\ndef _load_data(init_dict):\n \"\"\" Load dataset.\n \"\"\"\n # Auxiliary objects\n num_covars_out = init_dict['AUX']['num_covars_out']\n num_covars_cost = init_dict['AUX']['num_covars_cost']\n num_agents = init_dict['BASICS']['agents']\n\n is_object = (init_dict['ESTIMATION']['version'] == 'object')\n\n # Read dataset\n data = np.genfromtxt(init_dict['BASICS']['source'])\n\n # Reshaping, this ensure that the program also runs with just one agent\n # as otherwise only an vector is created. This creates problems for the\n # subsetting of the overall data into the components.\n data = np.array(data, ndmin=2)\n\n # Distribute data\n Y, D = data[:, 0], data[:, 1]\n\n X, Z = data[:, 2:(num_covars_out + 2)], data[:, -num_covars_cost:]\n\n # Create object-oriented version of sample\n agent_objs = None\n\n if is_object:\n\n agent_objs = []\n\n for i in range(num_agents):\n\n agent_obj = AgentCls()\n\n agent_obj.set_exogeneous_characteristics('cost', list(Z[i,:]))\n\n agent_obj.set_exogeneous_characteristics('outcome', list(X[i,:]))\n\n agent_obj.set_endogenous_characteristics('choice', int(D[i]))\n\n agent_obj.set_endogenous_characteristics('outcome', Y[i])\n\n agent_obj.set_economic_environment(init_dict)\n\n agent_obj.lock()\n\n agent_objs += [agent_obj]\n\n # Finishing\n return Y, D, X, Z, agent_objs\n\n\ndef _get_start(which, init_dict, Y, D, X, Z):\n \"\"\" Get different kind of starting values.\n \"\"\"\n # Antibugging.\n assert (which in ['random', 'init', 'auto'])\n\n # Distribute auxiliary objects\n num_paras = init_dict['AUX']['num_paras']\n num_covars_cost = init_dict['AUX']['num_covars_cost']\n\n # Construct auxiliary objects\n G = np.concatenate((X, Z[:, 1:]), axis=1)\n\n # Select relevant values.\n if which == 'random':\n x0 = np.random.uniform(size=num_paras)\n\n # Variances\n x0[(-4)] = max(x0[(-4)], 0.01)\n x0[(-3)] = max(x0[(-3)], 0.01)\n\n # Correlations\n x0[(-2)] -= 0.5\n x0[(-1)] -= 0.5\n\n elif which == 'init':\n x0 = np.array(init_dict['AUX']['init_values'][:])\n\n elif which == 'auto':\n\n # Subsetting\n Y1, X1 = Y[D == 1], X[(D == 1), :]\n olsRslt = sm.OLS(Y1, X1).fit()\n\n # Extract results\n coeffs_treated = olsRslt.params\n sd_treated = np.array(np.sqrt(olsRslt.scale))\n\n # Subsetting\n Y0, X0 = Y[D == 0], X[(D == 0), :]\n olsRslt = sm.OLS(Y0, X0).fit()\n\n # Extract results\n coeffs_untreated = olsRslt.params\n sd_untreated = np.array(np.sqrt(olsRslt.scale))\n\n # Estimate choice model\n probitRslt = sm.Probit(D, G).fit()\n sd = init_dict['COST']['sd']\n coeffs = probitRslt.params*sd\n\n # Special treatment of cost intercept\n cost_int = coeffs_treated[0] - coeffs_untreated[0] - coeffs[0]\n\n # Collect results\n x0 = np.concatenate((coeffs_treated, coeffs_untreated))\n x0 = np.concatenate((x0, [cost_int], -coeffs[-(num_covars_cost - 1):]))\n x0 = np.concatenate((x0, [sd_treated, sd_untreated]))\n x0 = np.concatenate((x0, [0.00, 0.00]))\n\n else:\n raise AssertionError\n\n # Document starting values\n init_dict['AUX']['start_values'] = x0.copy()\n\n # Transform to real line\n x0 = _transform_start(x0)\n\n # Type conversion\n x0 = np.array(x0)\n\n # Quality assurance.\n assert (np.all(np.isfinite(x0)))\n\n # Finishing.\n return x0\n\n\ndef _transform_start(x):\n \"\"\" Transform starting values to cover the whole real line.\n \"\"\"\n\n # Coefficients\n x[:(-4)] = x[:(-4)]\n\n # Variances\n x[(-4)] = np.log(x[(-4)])\n x[(-3)] = np.log(x[(-3)])\n\n # Correlations\n transform = (x[(-2)] + 1) / 2\n x[(-2)] = np.log(transform / (1.0 - transform))\n\n transform = (x[(-1)] + 1) / 2\n x[(-1)] = np.log(transform / (1.0 - transform))\n\n # Finishing\n return x\n\n\ndef _distribute_arguments(args):\n \"\"\" Distribute arguments for evaluation of criterion function and some\n auxiliary parameters.\n \"\"\"\n Y1_coeffs = np.array(args['TREATED']['all'])\n Y0_coeffs = np.array(args['UNTREATED']['all'])\n\n C_coeffs = np.array(args['COST']['all'])\n\n U1_sd = args['TREATED']['sd']\n U0_sd = args['UNTREATED']['sd']\n\n U1V_rho = args['DIST']['rho1']\n U0V_rho = args['DIST']['rho0']\n V_sd = args['COST']['sd']\n\n choice_coeffs = np.concatenate((Y1_coeffs - Y0_coeffs, - C_coeffs))\n\n # Finishing\n return Y1_coeffs, Y0_coeffs, C_coeffs, choice_coeffs, U1_sd, U0_sd, \\\n U1V_rho, U0V_rho, V_sd","sub_path":"lectures/economic_models/generalized_roy/private_package/grmpy/tools/optimization/estimation.py","file_name":"estimation.py","file_ext":"py","file_size_in_byte":12884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"25124091","text":"a=5 # a, b, total 전역변수\nb=7\ntotal=0\n\n\ndef calculate(x,y):\n total= x+y # 새로운 값이 할당되어 함수 안 total은 지역변수가 됨. \n print(\"In Function\")\n print(\"a:\",str(a), \"b:\", str(b), \"a+b:\", str(a+b), \"total:\", str(total))\n return total\n\n\n\ndef main():\n\n print(\"In Program - 1\")\n print(\"a:\", str(a), \"b:\", str(b), \"a+b:\",str(a+b))\n\n sum = calculate(a,b)\n print(\"After Calculation\")\n print(\"Total:\", str(total), \" Sum:\", str(sum)) # 지역 변수는 전역 변수에 영향을 주지 않음!\n\nif __name__== \"__main__\":\n main()","sub_path":"5/scoping_rule_final.py","file_name":"scoping_rule_final.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"619230270","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom sparseimage3d import *\n\nimport Image\n\nif __name__==\"__main__\":\n log.info(\"The scripts visualises histogram of values from Sparse 3D Image loaded from file.\")\n\n try: srcpath = sys.argv[1]\n except: log.err(\"Argument expected: path to the Sparse 3D Image file.\"); sys.exit(-1)\n\n log.info(\"loading from file \"+srcpath)\n sim3d = SparseImage3D()\n sim3d.load(open(srcpath))\n sim3d.hist(title=srcpath)\n \n","sub_path":"sparseimage3d_show_hist.py","file_name":"sparseimage3d_show_hist.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"240987867","text":"# extreme learning machine\r\n# Jarvis Xu\r\n\r\nimport numpy as np\r\nimport pandas as pd # mainly used for reading data from excel\r\nimport nltk # mainly used for eliminating the stop words\r\nfrom nltk.corpus import stopwords # ^\r\nfrom sklearn.metrics import confusion_matrix, recall_score, f1_score, precision_score\r\n\r\n# used to transform text data into \r\nfrom sklearn.feature_extraction.text import HashingVectorizer \r\n\r\n# preprocessing\r\n# X_train, y_train\r\n# X_test, y_test\r\n\r\n# load data from excel\r\ndef load(s):\r\n data = pd.read_excel('EMAILDATASET.xlsx')\r\n lst = list(data[s])\r\n return lst\r\n\r\n# eliminate stopword from a sentence\r\ndef removeStopWords(s,all_stopwords):\r\n text_tokens = nltk.word_tokenize(s)\r\n tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]\r\n newString = \" \".join(word for word in tokens_without_sw)\r\n return newString\r\n\r\n# convert text input into numbers\r\ndef X_convert(lst):\r\n # eliminate stopwords\r\n nltk.download('stopwords')\r\n all_stopwords = stopwords.words('english')\r\n X = []\r\n num_inputNodes = 1000 # this number controls the number of nodes in the input layer\r\n vectorizer = HashingVectorizer(n_features = num_inputNodes)\r\n print(\"The number of input nodes:\", num_inputNodes)\r\n for i in range(len(lst)):\r\n text = lst[i]\r\n text = [removeStopWords(text, all_stopwords)]\r\n vector = vectorizer.transform(text)\r\n X.append((vector.toarray())[0])\r\n return X\r\n\r\n# convert text desired output into numbers \r\ndef desiredOutput(lst):\r\n output = []\r\n for i in lst:\r\n if i == 'WFO': output.append(0)\r\n elif i == 'LOD': output.append(1)\r\n elif i == 'CLK': output.append(2)\r\n elif i == 'CLE': output.append(3)\r\n elif i == 'IDC': output.append(4)\r\n elif i == 'ADC': output.append(5)\r\n elif i == 'DPC': output.append(6)\r\n elif i == 'CTM': output.append(7)\r\n elif i == 'COF': output.append(8)\r\n elif i == 'CDT': output.append(9)\r\n elif i == 'RBK': output.append(10)\r\n elif i == 'BCL': output.append(11)\r\n elif i == 'MSD': output.append(12)\r\n elif i == 'RMB': output.append(13)\r\n else: output.append(0)\r\n return output\r\n\r\n# convert text desired output into numbers (subcategories)\r\ndef desiredOutput1(lst):\r\n output = []\r\n for i in lst:\r\n if i == 'ITD': output.append(0)\r\n elif i == 'OAA': output.append(1)\r\n elif i == 'OSL': output.append(2)\r\n else: output.append(0)\r\n return output\r\n\r\n# extract the test data from the complete set of data\r\ndef testSet(lst):\r\n test = []\r\n for i in range(240,255):\r\n test.append(lst[i])\r\n return test\r\n'''\r\n# print the actual results\r\ndef print_Result(D,A):\r\n D1 = 0\r\n A1 = 0\r\n for i in range(len(D)):\r\n print()\r\n'''\r\n\r\nclass ELM():\r\n # define input X, label y, number of neurons m, \r\n # contral parameter L = 0.2 and training function TRAIN_beta\r\n def __init__(self, X, y, m, L):\r\n self.X = X\r\n self.y = y\r\n self.m = m\r\n self.L = L\r\n self.TRAIN_beta()\r\n \r\n # use sigmoid function for feature mapping\r\n # transform input data into ELM feature space\r\n def sigmoid(self, x):\r\n return 1.0 / (1 + np.exp(-x))\r\n \r\n # define training function, random w, b\r\n # output matrix H, input weights beta\r\n # F1 output function\r\n def TRAIN_beta(self):\r\n n, d = self.X.shape\r\n self.w = np.random.rand(d, self.m)\r\n self.b = np.random.rand(1, self.m)\r\n H = self.sigmoid(np.dot(self.X,self.w) + self.b) # use feature mapping to get output matrix\r\n self.beta = np.dot(np.linalg.inv(np.identity(self.m) / self.L + np.dot(H.T, H)),\r\n np.dot(H.T, self.y))\r\n print('Train Finish', self.beta.shape,\"(# hidden nodes, # output nodes)\")\r\n\r\n# testing function\r\n def TEST(self, x):\r\n H = self.sigmoid(np.dot(x, self.w) + self.b) # use testing set\r\n result = np.dot(H, self.beta) \r\n # print('result= ',result)\r\n return result\r\n\r\nX_name = 'Text_Of_Email'\r\ny_name = 'Category'\r\nyy_name = 'Sub-Category'\r\nX = load(X_name)\r\ny = load(yy_name)\r\n\r\n# preprocessing for input data\r\nX_train = X_convert(X)\r\n# preprocessing for desired output\r\ny_train = desiredOutput(y)\r\n\r\nX_test = testSet(X_train)\r\ny_test = testSet(y_train) \r\n\r\nX_train = X_train[0:241]\r\ny_train = y_train[0:241]\r\nX_test1 = X_train[100:114]\r\ny_test1 = y_train[100:114]\r\n\r\n\r\nX_train = np.array(X_train)\r\ny_train = np.array(y_train)\r\nX_train1 = np.array(X_train)\r\ny_train1 = np.array(y_train)\r\nX_test = np.array(X_test)\r\ny_test = np.array(y_test)\r\nX_test1 = np.array(X_test)\r\ny_test1 = np.array(y_test)\r\n\r\n# training process\r\n# OneHot encode is used for training\r\nY_onehot = np.eye(14)[y_train]\r\nelm = ELM(X_train, Y_onehot, 8000, 0.2)\r\n\r\n'''\r\n# testing process\r\npredict = elm.TEST(X_test)\r\npredict = np.argmax(predict, axis = 1) # use OneHot encode, classify by the index with the greatest value\r\ny_test = np.eye(3)[y_test]\r\nacc = np.sum(predict == y_test)\r\nprint('acc :', acc)\r\nfor i in range(len(y_test)):\r\n print(y_test[i])\r\n print(predict[i])\r\n'''\r\n\r\n# testing process over training set\r\npredict = elm.TEST(X_train)\r\npredict = np.argmax(predict, axis = 1) # use OneHot encode, classify by the index with the greatest value\r\ny_train1 = np.eye(14)[y_train]\r\nc_m = confusion_matrix(y_train,predict)\r\nprint(\"confusion matrix for training set:\")\r\nprint(c_m)\r\nprint(\"precision score = \",precision_score(y_train,predict,average='micro'))\r\nprint(\"recall score = \",recall_score(y_train,predict,average='micro'))\r\nprint(\"f1 score = \",f1_score(y_train,predict,average='micro'))\r\n\r\n# testing process over testing set\r\npredict = elm.TEST(X_test1)\r\npredict = np.argmax(predict, axis = 1) # use OneHot encode, classify by the index with the greatest value\r\ny_test1 = np.eye(14)[y_test]\r\n# Confusion matrix for testing set\r\nc_m = confusion_matrix(y_test,predict)\r\nprint(\"confusion matrix for testing set:\")\r\nprint(c_m)\r\nprint(\"precision score = \",precision_score(y_test,predict,average='micro'))\r\nprint(\"recall score = \",recall_score(y_test,predict,average='micro'))\r\nprint(\"f1 score = \",f1_score(y_test,predict,average='micro'))\r\n# print(y_test)\r\n# print(predict)\r\nprecision = 0\r\nrecall = 0\r\nf1 = 0\r\niter = 100\r\nfor i in range(iter):\r\n Y_onehot = np.eye(14)[y_train]\r\n elm = ELM(X_train, Y_onehot, 2000, 0.2)\r\n # testing process over testing set\r\n predict = elm.TEST(X_test1)\r\n predict = np.argmax(predict, axis = 1) # use OneHot encode, classify by the index with the greatest value\r\n y_test1 = np.eye(14)[y_test] \r\n precision = precision + precision_score(y_test,predict,average='micro')\r\n recall = recall + recall_score(y_test,predict,average='micro')\r\n f1 = f1+ f1_score(y_test,predict,average='micro')\r\nprint(\"average precision:\", precision/iter)\r\nprint(\"average recall:\", recall/iter)\r\nprint(\"average f1:\", f1/iter)\r\n\r\n'''\r\n# now the raw data is ready to be used-----------------------------\r\nX_train = np.array(X_train)\r\ny_train = np.array(y_train)\r\nX_test = np.array(X_test)\r\ny_test = np.array(y_test)\r\n'''\r\n","sub_path":"elm_subcategory_JarvisX.py","file_name":"elm_subcategory_JarvisX.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"266099294","text":"from __future__ import division\nimport numpy as np\nfrom petsc4py import PETSc\nimport time\n\ndef normalise(a):\n \"\"\"\n Normalise the given petsc vector a\n \"\"\"\n a.shape = (-1, 3)\n b = np.sqrt(a[:, 0] ** 2 + a[:, 1] ** 2 + a[:, 2] ** 2)\n ids = (b == 0)\n b[ids] = 1.0\n a[:, 0] /= b\n a[:, 1] /= b\n a[:, 2] /= b\n a.shape = (-1,)\n\ndef init_vector_array(mesh, m0, norm=False, start=-1, N=-1):\n if N < 0:\n N = mesh.n\n if start < 0:\n start = mesh.start\n\n spin = np.zeros((N, 3))\n if isinstance(m0, list) or isinstance(m0, tuple):\n spin[:, :] = m0\n spin = np.reshape(spin, 3 * N, order='C')\n\n elif hasattr(m0, '__call__'):\n for i in range(N):\n v = m0(mesh.coordinates[i+start])\n if len(v) != 3:\n raise Exception(\n 'The length of the value in init_vector method must be 3.')\n spin[i, :] = v[:]\n spin = np.reshape(spin, 3 * mesh.n, order='C')\n\n elif isinstance(m0, np.ndarray):\n if m0.shape == (3, ):\n spin[:] = m0 # broadcasting\n else:\n spin.shape = (-1)\n spin[:] = m0 # overwriting the whole thing\n\n spin.shape = (-1,)\n\n if norm:\n normalise(spin)\n\n return spin\n\ndef init_vector_field(vec, mesh, init, norm=False):\n spin = init_vector_array(mesh, init, norm=norm)\n start, stop = vec.getOwnershipRange()\n ids = np.array([i for i in range(start, stop)], dtype=np.int32)\n vec.setValues(ids, spin)\n vec.assemble()\n\ndef create_vector_field(mesh, init=None, norm=False):\n vec = PETSc.Vec().create(comm=mesh.comm)\n vec.setSizes((mesh.v_n, 3*mesh.number_nodes))\n vec.setUp()\n if init is not None:\n init_vector_field(vec, mesh, init, norm)\n return vec\n\ndef init_scalar_array(mesh, value):\n\n n = mesh.n\n mesh_v = np.zeros(n)\n\n if isinstance(value, (int, float)):\n mesh_v[:] = value\n elif hasattr(value, '__call__'):\n start = mesh.start\n for i in range(n):\n mesh_v[i] = value(mesh.coordinates[i+start])\n elif isinstance(value, np.ndarray):\n if value.shape == mesh_v.shape:\n mesh_v[:] = value[:]\n\n return mesh_v\n\ndef init_scalar_field(vec, mesh, init):\n value = init_vector_array(mesh, init, norm=norm)\n start, stop = vec.getOwnershipRange()\n ids = np.array([i for i in range(start, stop)], dtype=np.int32)\n vec.setValues(ids, value)\n vec.assemble()\n\ndef create_scalar_field(mesh, init=None):\n vec = PETSc.Vec().create(comm=mesh.comm)\n vec.setSizes((mesh.n, mesh.number_nodes))\n vec.setUp()\n if init is not None:\n init_scalar_field(vec, mesh, init)\n vec.assemble()\n return vec\n\ndef get_all_data_from_vec(m, comm, root=0):\n \"\"\"\n collect the distributed vector to a numpy array, for debug propose\n unforuntely, vec.getValues only can fetch local values\n \"\"\"\n rank = comm.Get_rank()\n size = comm.Get_size()\n start, stop = m.getOwnershipRange()\n data = [start, stop, m.array]\n if rank!=root:\n comm.send(data, dest=root, tag=rank)\n return None\n else:\n m_array = np.zeros(m.getSize(), dtype=np.float)\n m_array[start:stop] = m.array[:]\n for i in range(size):\n if i != root:\n data = comm.recv(source=i, tag=i)\n start, stop, v = data\n m_array[start:stop] = v[:]\n return m_array\n\ndef compute_L_Ms(mesh, Ms):\n ndv_Ms = np.zeros(mesh.number_nodes, dtype=np.float)\n cv = mesh.cell_verts\n for k in range(4):\n for i in range (mesh.number_cells):\n ndv_Ms[cv[i, k]] += Ms[i]*mesh.volumes[i]/4.0\n\n ndv_Ms_v = []\n for v in ndv_Ms:\n ndv_Ms_v.append(v)\n ndv_Ms_v.append(v)\n ndv_Ms_v.append(v)\n ndv_Ms_v = np.array(ndv_Ms_v)\n\n L_mu = create_vector_field(mesh)\n\n start, stop = L_mu.getOwnershipRange()\n ids = np.array([i for i in range(start, stop)], dtype=np.int32)\n L_mu.setValues(ids, ndv_Ms_v[ids])\n\n return L_mu\n","sub_path":"mumag/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"532137675","text":"import warnings\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import Point\n\nfrom autocnet.matcher import subpixel as sp\n\nfrom plio.io.io_controlnetwork import to_isis, write_filelist\n\ndef subpixel_match(cg, cn,threshold=0.9, template_size=19, search_size=53, max_x_shift=1.0,max_y_shift=1.0, **kwargs):\n\n def subpixel_group(group, threshold=0.9, template_size=19, search_size=53, max_x_shift=1.0,max_y_shift=1.0, **kwargs):\n offs = []\n for i,(idx, r) in enumerate(group.iterrows()):\n if i == 0:\n x = r.x\n y = r.y\n offs.append([0,0, np.inf])\n continue\n\n e = r.edge\n s_img = cg.edge[e[0]][e[1]].source.geodata\n s_template = sp.clip_roi(s_img, (x, y), template_size)\n #s_template = cv2.Canny(bytescale(s_template), 50,100) # Canny - bad idea\n d_img = cg.edge[e[0]][e[1]].destination.geodata\n d_search = sp.clip_roi(d_img, (r.x, r.y), search_size)\n #d_search = cv2.Canny(bytescale(d_search), 50,100)\n\n xoff,yoff,corr = sp.subpixel_offset(s_template, d_search, **kwargs)\n offs.append([xoff,yoff,corr])\n df = pd.DataFrame(offs, columns=['x_off', 'y_off', 'corr'], index=group.index)\n return df\n gps = cn.data.groupby('point_id').apply(subpixel_group,threshold=0.9,max_x_shift=5, max_y_shift=5,template_size=template_size, search_size=search_size,**kwargs)\n cn.data[['x_off', 'y_off', 'corr']] = gps.reset_index()[['x_off', 'y_off', 'corr']]\n\ndef identify_potential_overlaps(cg, cn, overlap=True):\n \"\"\"\n Identify those points that could have additional measures\n\n Parameters\n ----------\n overlap : boolean\n If True, apply aprint(g)n additional point in polygon check, where\n the polygon is the footprint intersection between images and\n the point is a keypoint projected into lat/lon space. Note\n that the projection can be inaccurate if the method used\n estimates the transformation.\n\n Returns\n -------\n candidate_cliques : DataFrame\n with the index as the point id (in the data attribute)\n and the value as an iterable of image ids to search\n for a new point.\n \"\"\"\n\n\n fc = cg.compute_fully_connected_components()\n\n candidate_cliques = []\n geoms = []\n idx = []\n for i, p in cn.data.groupby('point_id'):\n # Which images are covered already. This finds any connected cycles that\n # a node is in (this can be more than one - an hourglass network for example)\n # Extract the fully connected subgraph for each covered image in order to\n # identify which subgraph the measure is in\n covered = p['image_index']\n candidate_cycles = [fc[c] for c in covered]\n cycle = [i for i in candidate_cycles if candidate_cycles.count(i) > 1]\n cycle_to_punch = cycle[0][0]\n\n # Using the cycles to punch, which images could also be covered?\n uncovered = tuple(set(cycle_to_punch).difference(set(covered)))\n\n # All candidates are covered, skip this point\n if not uncovered:\n continue\n\n # Determine whether a 'real' lat/lon are to be used and reproject\n if overlap:\n row = p.iloc[0]\n lat, lon = cg.node[row.image_index]['data'].geodata.pixel_to_latlon(row.x, row.y)\n else:\n lat, lon = 0,0\n\n # Build the data for the geodataframe - can the index be cleaner?\n geoms.append(Point(lon, lat))\n candidate_cliques.append([uncovered, cycle_to_punch])\n idx.append(i)\n\n\n candidate_cliques = gpd.GeoDataFrame(candidate_cliques, index=idx,\n columns=['candidates', 'subgraph'], geometry=geoms)\n\n def overlaps(group):\n \"\"\"\n Take a group, find the subgraph, compute the intersection of footprints\n and apply a group point in polygon check. This is an optimization where\n n-points are intersected with the poly at once (as opposed to the\n single iteration approach.)\n \"\"\"\n cycle_to_punch = group.subgraph.iloc[0]\n subgraph = cg.create_node_subgraph(cycle_to_punch)\n union, _ = subgraph.compute_intersection(cycle_to_punch[0])#.query('overlaps_all == True')\n intersection = group.intersects(union.unary_union)\n return intersection\n\n # If the overlap check is going to be used, apply it.\n if overlap:\n candidate_cliques['overlap'] = False\n for i, g in candidate_cliques.groupby('candidates'):\n intersection = overlaps(g)\n candidate_cliques.loc[intersection.index, 'overlap'] = intersection\n return candidate_cliques.query('overlap == True')['candidates']\n else:\n return candidate_cliques.candidates\n\ndef deepen_correspondences(cg, cn):\n pass\n\nclass ControlNetwork(object):\n measures_keys = ['point_id', 'image_index', 'keypoint_index', 'edge', 'match_idx', 'x', 'y', 'x_off', 'y_off', 'corr', 'valid']\n\n def __init__(self):\n self._point_id = 0\n self._measure_id = 0\n self.measure_to_point = {}\n self.data = pd.DataFrame(columns=self.measures_keys)\n\n @classmethod\n def from_candidategraph(cls, matches):\n cls = ControlNetwork()\n for match in matches:\n for idx, row in match.iterrows():\n edge = (row.source_image, row.destination_image)\n source_key = (row.source_image, row.source_idx)\n source_fields = row[['source_x', 'source_y']]\n destin_key = (row.destination_image, row.destination_idx)\n destin_fields = row[['destination_x', 'destination_y']]\n if cls.measure_to_point.get(source_key, None) is not None:\n tempid = cls.measure_to_point[source_key]\n cls.add_measure(destin_key, edge, row.name, destin_fields, point_id=tempid)\n elif cls.measure_to_point.get(destin_key, None) is not None:\n tempid = cls.measure_to_point[destin_key]\n cls.add_measure(source_key, edge, row.name, source_fields, point_id=tempid)\n else:\n cls.add_measure(source_key, edge, row.name, source_fields)\n cls.add_measure(destin_key, edge,row.name, destin_fields)\n cls._point_id += 1\n\n cls.data.index.name = 'measure_id'\n return cls\n\n def add_measure(self, key, edge, match_idx, fields, point_id=None):\n \"\"\"\n Create a new measure that is coincident to a given point. This method does not\n create the point if is missing. When a measure is added to the graph, an associated\n row is added to the measures dataframe.\n\n Parameters\n ----------\n key : hashable\n Some hashable id. In the case of an autocnet graph object the\n id should be in the form (image_id, match_id)\n\n point_id : hashable\n The point to link the node to. This is most likely an integer, but\n any hashable should work.\n \"\"\"\n if key in self.measure_to_point.keys():\n return\n if point_id == None:\n point_id = self._point_id\n self.measure_to_point[key] = point_id\n # The node_id is a composite key (image_id, correspondence_id), so just grab the image\n image_id = key[0]\n match_id = key[1]\n self.data.loc[self._measure_id] = [point_id, image_id, match_id, edge, match_idx, *fields, 0, 0, np.inf, True]\n self._measure_id += 1\n\n def remove_measure(self, idx):\n self.data = self.data.drop(self.data.index[idx])\n for r in idx:\n self.measure_to_point.pop(r, None)\n\n def validate_points(self):\n \"\"\"\n Ensure that all control points currently in the nework are valid.\n\n Criteria for validity:\n\n * Singularity: A control point can have one and only one measure from any image\n\n Returns\n -------\n : pd.Series\n\n \"\"\"\n\n def func(g):\n # One and only one measure constraint\n if g.image_index.duplicated().any():\n return True\n else: return False\n return self.data.groupby('point_id').apply(func)\n\n def clean_singles(self):\n \"\"\"\n Take the `data` dataframe and return only those points with\n at least two measures. This is automatically called before writing\n as functions such as subpixel matching can result in orphaned measures.\n \"\"\"\n return self.data.groupby('point_id').apply(lambda g: g if len(g) > 1 else None)\n\n def to_isis(self, outname, serials, olist, *args, **kwargs): #pragma: no cover\n \"\"\"\n Write the control network out to the ISIS3 control network format.\n \"\"\"\n\n if self.validate_points().any() == True:\n warnings.warn('Control Network is not ISIS3 compliant. Please run the validate_points method on the control network.')\n return\n\n # Apply the subpixel shift\n self.data.x += self.data.x_off\n self.data.y += self.data.y_off\n\n to_isis(outname + '.net', self.data.query('valid == True'),\n serials, *args, **kwargs)\n write_filelist(olist, outname + '.lis')\n\n # Back out the subpixel shift\n self.data.x -= self.data.x_off\n self.data.y -= self.data.y_off\n\n def to_bal(self):\n \"\"\"\n Write the control network out to the Bundle Adjustment in the Large\n (BAL) file format. For more information see:\n http://grail.cs.washington.edu/projects/bal/\n \"\"\"\n pass\n","sub_path":"autocnet/control/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":9857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"62935877","text":"import os\nfrom flask import Flask, redirect, send_file, request\nfrom flask_socketio import SocketIO, emit, join_room, leave_room, send\nfrom . import first\nfrom . import webapp_2\nfrom . import sg_test_env\nfrom . import test_forms\n\nsocketio = SocketIO()\n\n\nblueprints = [\n first,\n webapp_2,\n sg_test_env,\n test_forms\n]\n\ndef create_app(debug=False):\n \"\"\"Create an application.\"\"\"\n global _app\n app = Flask(__name__)\n app.debug = debug\n app.config['SECRET_KEY'] = 'gjr39dkjn344_!67\"@'\n\n app.template_folder = os.path.abspath(\n './src/{0}/templates').format('/'.join(__name__.split('.'))\n )\n app.static_folder = os.path.abspath(\n './src/{0}/static').format('/'.join(__name__.split('.'))\n )\n\n return app\n\ndef _init_root(app):\n @app.route('/', methods=['GET', 'POST'])\n def root():\n \"\"\"Route the frontend.\"\"\"\n return redirect('/static/index.html')\n\n @app.route('/index', methods=['GET', 'POST'])\n def index():\n \"\"\"Route the frontend.\"\"\"\n return redirect('/')\n\n @app.route('/index.html', methods=['GET', 'POST'])\n def index_html():\n \"\"\"Route the frontend.\"\"\"\n return redirect('/')\n \n # @app.route('/